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 you will get onViewCreated() override method where you should always initialize your views as in this method you get view object using which you can find your views like :
@Override
public void onViewCreated(View view, Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
view.findViewById(R.id.yourId).setOnClickListener(this);
// or
getActivity().findViewById(R.id.yourId).setOnClickListener(this);
}
Always remember in case of Fragment that onViewCreated()
method will not called automatically if you are returning null or super.onCreateView()
from onCreateView()
method.
It will be called by default in case of ListFragment
as ListFragment
return FrameLayout
by default.
Note: you can get the fragment view anywhere in the class by using getView()
once onCreateView()
has been executed successfully.
i.e.
getView().findViewById("your view id");