I am trying to create an ImageView in a Fragment which will refer to the ImageView element which I have created in the XML for the Fragment. However, the findViewById<
You could also do it in the onActivityCreated
Method.
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
}
Like they do here: http://developer.android.com/reference/android/app/Fragment.html (deprecated in API level 28)
getView().findViewById(R.id.foo);
and
getActivity().findViewById(R.id.foo);
are possible.
Note :
From API Level 26, you also don't need to specifically cast the result of findViewById as it uses inference for its return type.
So now you can simply do,
public View onCreateView(LayoutInflater inflater,
ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.testclassfragment, container, false);
ImageView imageView = view.findViewById(R.id.my_image); //without casting the return type
return view;
}
In fragments we need a view of that window so that we make a onCreateView of this Fragment.
Then get the view and use it to access each and every view id of that view elements..
class Demo extends Fragment
{
@Override
public View onCreateView(final LayoutInflater inflater,ViewGroup container, Bundle savedInstanceState)
{
View view =inflater.inflate(R.layout.demo_fragment, container,false);
ImageView imageview=(ImageView)view.findViewById(R.id.imageview1);
return view;
}
}
getView()
will give the root view
View v = getView().findViewByID(R.id.x);
You can call findViewById()
with the Activity Object you get inside your public void onAttach(Activity activity)
method inside your Fragment.
Save the Activity into a variable for example:
In the Fragment class:
private Activity mainActivity;
In the onAttach()
method:
this.mainActivity=activity;
Finally execute every findViewById through the vairable:
mainActivity.findViewById(R.id.TextView);
agreed with calling findViewById()
on the View.
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View V = inflater.inflate(R.layout.testclassfragment, container, false);
ImageView imageView = (ImageView) V.findViewById(R.id.my_image);
return V;
}