Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

findViewById in Fragment

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 method only works if I extend an Activity class. Is there anyway of which I can use it in Fragment as well?

public class TestClass extends Fragment {     public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {         ImageView imageView = (ImageView)findViewById(R.id.my_image);         return inflater.inflate(R.layout.testclassfragment, container, false);     } } 

The findViewById method has an error on it which states that the method is undefined.

like image 852
simplified. Avatar asked Jun 27 '11 16:06

simplified.


People also ask

Can you use findViewById in fragment?

Using getView() returns the view of the fragment, then you can call findViewById() to access any view element in the fragment view.

How do I use findViewById in fragment in Kotlin?

Step 1 − Create a new project in Android Studio, go to File ⇒ New Project and fill all required details to create a new project. Step 2 − Add the following code to res/layout/activity_main. xml.

What is the purpose of the findViewById () method?

FindViewById<T>(Int32)Finds a view that was identified by the id attribute from the XML layout resource.


1 Answers

Use getView() or the View parameter from implementing the onViewCreated method. It returns the root view for the fragment (the one returned by onCreateView() method). With this you can call findViewById().

@Override public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {     ImageView imageView = (ImageView) getView().findViewById(R.id.foo);     // or  (ImageView) view.findViewById(R.id.foo);  

As getView() works only after onCreateView(), you can't use it inside onCreate() or onCreateView() methods of the fragment .

like image 171
advantej Avatar answered Oct 04 '22 13:10

advantej