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<
Inside Fragment
class we get onViewCreated()
override method where we should always initialize our views because in this method we get view
object. Using this object we can find our views like below:
class MyFragment extends Fragment {
private ImageView imageView;
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
return inflater.inflate(R.layout.my_fragment_layout, container, false);
}
@Override
public void onViewCreated(View view, Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
//initialize your view here for use view.findViewById("your view id")
imageView = (ImageView) view.findViewById(R.id.my_image);
}
}
getView()
works only after onCreateView()
completed, so invoke it from onPostCreate()
:
@Override
public void onPostCreate(Bundle savedInstanceState) {
super.onPostCreate(savedInstanceState);
ImageView imageView = (ImageView) getView().findViewById(R.id.foo);
}
Using getView()
returns the view of the fragment, then you can call findViewById()
to access any view element in the fragment view.
Inside onCreateView method
1) first you have to inflate the layout/view you want to add eg. LinearLayout
LinearLayout ll = inflater.inflate(R.layout.testclassfragment, container, false);
2) Then you can find your imageView id from layout
ImageView imageView = (ImageView)ll.findViewById(R.id.my_image);
3)return the inflated layout
return ll;
Try this it works for me
public class TestClass extends Fragment {
private ImageView imageView;
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.testclassfragment, container, false);
findViews(view);
return view;
}
private void findViews(View view) {
imageView = (ImageView) view.findViewById(R.id.my_image);
}
}
You have to inflate the view
public class TestClass extends Fragment {
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
}}