NikanDalvand NikanDalvand - 1 month ago 16
Android Question

Finding Include view and updating TextView

I have a fragment which inside of it i have

<include layout="@layout/card" android:id="@+id/card" />
<include layout="@layout/card" android:id="@+id/card1" />
<include layout="@layout/card" android:id="@+id/card2" />


And my card xml is just a simple card as below

<LinearLayout
android:layout_height="match_parent"
android:layout_width="match_parent"
android:orientation="horizontal"
android:gravity="left|center_vertical">

<TextView
android:id="@+id/title"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:maxLines="3"
android:padding="8dp"
android:text="Item Color"
android:textColor="#222"
android:textStyle="bold"
android:textSize="18dp"
android:gravity="center_vertical"/>

</LinearLayout>


What im trying to do in my java fragment is loading the first card include and chnage its text view text
This is what i tried but it returns null

View card1 = getActivity().findViewById(R.id.card1);
TextView ct1 = (TextView) card1.findViewById(R.id.title);


So how can i achieve my goal or fix this problem?
Thanks for your time and help , appreciate it
**** update :
Heres the whole fragment

public class Home_Fragment extends Fragment {
@Override
public View onCreateView(LayoutInflater inflater,
ViewGroup container, Bundle savedInstanceState) {

//Inflate the layout for this fragment
ViewGroup card1 = (ViewGroup) getActivity().findViewById(R.id.card1);
TextView ct1 = (TextView) card1.findViewById(R.id.title);
ct1.setText("hey :P");

return inflater.inflate(
R.layout.home_fragment, container, false);

}
}

Answer

use .findViewById(R.id.card1); on the content view of the Fragment instead on getActivity()

public View onCreateView(LayoutInflater inflater,
  ViewGroup container, Bundle savedInstanceState) {
   View contentView = inflater.inflate(
          R.layout.home_fragment, container, false);
   //Inflate the layout for this fragment
     ViewGroup card1 = (ViewGroup)  contentView.findViewById(R.id.card1);
          TextView ct1 = (TextView) card1.findViewById(R.id.title);
          ct1.setText("hey :P");

  return contentView;

}

Comments