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.

30 Answers 11

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 .

292 upvote
  flag
Note: it's works only after onCreateView(). So, you can't use this in onCreate() – Dmitry Zaytsev
5 upvote
  flag
so what is the function I can override to implement this if onCreate is not the right place ? – Nico AD
15 upvote
  flag
This doesn't help if the ImageView is coming from the inflated layout - see my answer for details. Otherwise, onCreateView is the right place to do this @N-AccessDev – MattJenko
22 upvote
  flag
The best place to do this the onViewCreated method – advantej
1 upvote
  flag
you can't use getActivity and findViewById there in onCreate() or onCreateView either because they both come before onActivityCreated() which is when you are guaranteed that the activity view heirarchy has been created. – Jon
32 upvote
  flag
The documentation states that onActivityCreated() is the recommended place to find and store references to your views. You must clean up these stored references by setting them back to null in onDestroyView() or you will leak the Activity. – Monstieur
upvote
  flag
this doesn't work as getView() returns null – stack247
upvote
  flag
It works but I don't get why: I understand that findViewById() works in the scope of an Activity object because it is defined in the Activity class. As explained in this answer, in order to use it in a fragment we need to call it on getView() but... why? Isn't getView() just going to return a View as opposed to an Activity? ... I understand getActivity.findViewById() but getView.findViewById() ??? – jj_
1 upvote
  flag
getView might return null. LeffelMania has a better solution. – Confuse
upvote
  flag
We can also get the view reference through onViewCreated method.. – Raja Jawahar
2 upvote
  flag
@Locutus You must clean up these stored references by setting them back to null in onDestroyView() or you will leak the Activity reference please? – Muhammad Babar
upvote
  flag
@RobbyPatel Your edits made the code crash – cricket_007
upvote
  flag
@cricket_007 ok show me your code – RobbyPatel
1 upvote
  flag
@RobbyPatel I've correct the answer now. No need. – cricket_007
upvote
  flag
ok can i show your code? @cricket_007 – RobbyPatel
upvote
  flag
@cricket_007 getview work in onCreateview() in fragment – RobbyPatel
1 upvote
  flag
@RobbyPatel There's no possible way it can. It will return null. – cricket_007
upvote
  flag
@cricket_007 here is another issue my code is completely good – RobbyPatel
upvote
  flag
Actually you can make it work inside onCreateView() if you capture the view instance as View rootView = inflater.inflate(R.layout.your_fragment_layout, container, false); and do rootView.findViewById() after that – Pulak
upvote
  flag
@NoLuck, Yes, but that's what the other answers are for – cricket_007
upvote
  flag

You need to inflate the Fragment's view and call findViewById() on the View it returns.

public View onCreateView(LayoutInflater inflater, 
                         ViewGroup container, 
                         Bundle savedInstanceState) {
     View view = inflater.inflate(R.layout.testclassfragment, container, false);
     ImageView imageView = (ImageView) view.findViewById(R.id.my_image);
     return view;
}
4 upvote
  flag
When you do V.findViewById(R.id.someid),surely that will only work for all the widgets that are in the inflated view. What if the imageView he is trying to inflate is outside the inflated view? – Raunak
17 upvote
  flag
Then the class that "owns" and inflated the imageView needs to provide public access to it. That is very bad practice though. Fragments should only have access to the UI elements present in their layout. – LeffelMania
upvote
  flag
Note that findViewById has to be called on the view that is inflated, not on getView() – Nimesh Madhavan
upvote
  flag
For future readers: this method does not work. It just raises a android.view.ViewRootImpl$CalledFromWrongThreadException. – MrAsterisco
1 upvote
  flag
Looks like there's something wrong in your code (updating UI from a background thread), not mine. – LeffelMania
1 upvote
  flag
Thanks, it was useful. As unrelated comment: try to stick to Java naming conventions in your code. "V" does not look like a variable name in Java. – altumano
3 upvote
  flag
This should be the right answer. The accepted one leaves you with NullPointerException. – Machado
upvote
  flag
This should be the most voted, since is the correct answer. The one by advantej is wrong, since the layout hasn't been inflated before the getView() – George
upvote
  flag
@Raunak You are correct inflater.inflate(R.layout.yourdialogfragment, null).findViewById(R.id.someidfromfragmentdialog) will only return widgets that are in the fragment. If you want to get widgets from the host activity (the activity that spawned the DialogFragment) you have to use getActivity().findViewById(R.id.someidfromhostlayout) – Aleksey Khivrenko
upvote
  flag
@Raunak Thanks for the comment. I was wondering out aloud why the accepted answer does not use the view returned by the inflater. This discussion has clarified my doubt. – user30646

Get first the fragment view and then get from this view your ImageView.

public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
    View view = inflater.inflate(R.layout.testclassfragment, container, false);
    ImageView imageView = (ImageView) view.findViewById(R.id.my_image);
    return view;
}
upvote
  flag
So, does onCreate method is useful in a Fragment ? – Tsunaze
upvote
  flag
onCreateView creates and returns the view hierarchy associated with the fragment.onCreate is called to do initial creation of the fragment. Indeed, it depends on what you write in these methods. – xevincent
upvote
  flag
Okay, but how can i declare variable in the onCreate ? Because the View is inside the onCreateView method . – Tsunaze
upvote
  flag
@Tsunaze did you ever find out how to do this from the onCreate method? – StuStirling
upvote
  flag
This answer should be marked as the solution. – ulughbekula
upvote
  flag
I agree. This answer should be marked as the solution. – Boris Karloff

You can override onViewCreated() which is called right after all views had been inflated. It's the right place to fill in your Fragment's member View variables. Here's an example:

class GalleryFragment extends Fragment {
    private Gallery gallery;

    (...)

    @Override
    public void onViewCreated(View view, Bundle savedInstanceState) {
        gallery = (Gallery) view.findViewById(R.id.gallery);
        gallery.setAdapter(adapter);
        super.onViewCreated(view, savedInstanceState);
    }
}

I realise this is an old question, but the prevailing answer leaves something to be desired.

The question is not clear what is required of imageView - are we passing it back as the view, or merely saving a reference for later?

Either way, if the ImageView is coming from the inflated layout, the correct way to do this would be:

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;
    }
}
upvote
  flag
How then would you update imageView from ListFragment? Would this require FragmentManager? In other words, how can you update the imageView in a detail fragment from a separate class's onListItemClick? – whyoz
upvote
  flag
You would either save a reference to the imageView somewhere handy, or fragment.getView().findViewById(R.id.my_image) when you need it. In a ListFragment, assuming the image is in a list item, you would generally create a reference holder with the setTag/getTag methods of the list view item in your Adapter's getView method - there are many examples of how to do this. – MattJenko

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;
}

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

3 upvote
  flag
the view is not the activity – Steve M
upvote
  flag
corrected my answer – Mahmoud Badri

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

getView().findViewById(R.id.foo);

and

getActivity().findViewById(R.id.foo);

are possible.

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");
3 upvote
  flag
I am surprised not a lot of people have upvoted this response--this is the correct way to setup listeners on fragments... Perhaps this was a new development in the API. – Sonny
upvote
  flag
Using view passed to onViewCreated still causes NullPointerException but using getActivity() is fine. Any ideas why? – dVaffection
upvote
  flag
@dVaffection It may be that you are not returning a non null view in onCreateView() lifecycle method of fragment. Now in case of getActivity you are getting views from your activity rather than fragment main view depends upon what id you are passing. Please check are you returning a non null view from onCreateView or not? Then let me know. – Ankur Chaudhary
upvote
  flag
@AnkurChaudhary I return view from onCreateView method. I've just debugged and it turns out there is a layout (in my case FrameLayout). That being said when I try to find an element it returns null. Why is it happening? – dVaffection
upvote
  flag
@dVaffection can you please share your class of fragment and corresponding layout. – Ankur Chaudhary
upvote
  flag
upvote
  flag
In particular ListActivityFragment.java line 63 (FloatingActionButton) getActivity().findViewById(R.id.floating_new_item); – dVaffection
upvote
  flag
@dVaffection i have gone through your code and as you are returning super.oncreateView() which returns null. Another point is when you return null from onCreateView, onViewCreated() method will not be called automatically. Yes you can call it manually. Means onViewCreated will not be called if you are returning null or super method calling. That's why when you are trying to get any view from fragment it's returning null to you. – Ankur Chaudhary
upvote
  flag
@AnkurChaudhary What you're saying is valid if you inherit from Fragment, in my case I extend ListFragment which actually returns FrameLayout. – dVaffection
upvote
  flag
@dVaffection I checked the layout that ListFragment is using and there is no such view with the id 'floating_new_item'. So it's pretty clear that if you will try to access such field which is not in your layout then it'll return null. Now let me know that is your activity having this id field or not as you are using fragment_list layout in your activity. – Ankur Chaudhary
upvote
  flag
This is the correct method to use. – hitch.united

The method getView() wont work on fragments outside OnCreate and similar methods.

You have two ways, pass the view to the function on the oncreate (what means you can only run your functions when the view is being created) or set the view as a variable:

private View rootView;

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
    Bundle savedInstanceState) {
    rootView = inflater.inflate(R.layout.fragment_contatos, container, false);
}

public void doSomething () {
    ImageView thumbnail = (ImageView) rootView.findViewById(R.id.someId);
}

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);

The best way to implement this is as follows:

public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {

rootView = inflater.inflate(R.layout.testclassfragment, container, false);
        ImageView imageView = (ImageView) rootView.findViewById(R.id.my_image);
        return rootView
}

In this way, the rootView can be used for each control defined in the xml layout and the code is much cleaner in this way.

Hope this helps :)

upvote
  flag
i thinked this could be posiible, but , it didn't work – Mike Brian Olivera

getView() will give the root view

View v = getView().findViewByID(R.id.x); 

According to the documentation on API level 11

Reference, in Back Stack http://developer.android.com/reference/android/app/Fragment.html

short code

/**
 * The Fragment's UI is just a simple text view showing its
 * instance number.
 */
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
        Bundle savedInstanceState) {
    View v = inflater.inflate(R.layout.hello_world, container, false);
    View tv = v.findViewById(R.id.text);
    ((TextView)tv).setText("Fragment #" + mNum);
    tv.setBackgroundDrawable(getResources().getDrawable(android.R.drawable.gallery_thumb));
    return v;
}
EditText name = (EditText) getView().findViewById(R.id.editText1);
EditText add = (EditText) getView().findViewById(R.id.editText2);  

Use gradle skeleton plugin, it will automatically generate the view holder classes with the reference to your layout.

public class TestClass extends Fragment {
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        MyLayout myLayout = new MyLayout(inflater, container, false);
        myLayout.myImage.setImageResource(R.drawable.myImage);
        return myLayout.view;
    }
}

Now assuming you had an ImageView declared in your my_layout.xml file, it will automatically generate myLayout class for you.

Use

imagebutton = (ImageButton) getActivity().findViewById(R.id.imagebutton1);

imageview = (ImageView) getActivity().findViewById(R.id.imageview1);

it will work

Timing of transaction after .commit() may also cause this issue

I got the same issue (View in a Fragment could not be reached). The reason turned out to be, that - immediately after (FragmentTransaction).commit() -, the View had not been activated in the UI. There is no guarantee when, after .commit(), the transaction takes place; it's only queued. So I added a (FragmentManager).executePendingTransactions() to force the transaction to be done. After that, referencing the View works as expected !

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;
upvote
  flag
This is identical to LeffelMania's answer. – Reti43

There is one more method called onViewCreated.

@Override
public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
    super.onViewCreated(view, savedInstanceState);
    ImageView imageView = (ImageView) view.findViewById(R.id.imageview1);
}

1) Declare your layout file.

public View onCreateView(LayoutInflater inflater,ViewGroup container, 
                                 Bundle savedInstanceState) {
    return inflate(R.layout.myfragment, container, false);
}

2)Then, get the id of your view

@Override
public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
    super.onViewCreated(view, savedInstanceState);
    TextView nameView = (TextView) view.findViewById(R.id.textview1);
}

Try This:

View v = inflater.inflate(R.layout.testclassfragment, container, false);
ImageView img = (ImageView) v.findViewById(R.id.my_image);

return v;

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
}}

try

private View myFragmentView;

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) 
{
myFragmentView = inflater.inflate(R.layout.myLayoutId, container, false);
myView = myFragmentView.findViewById(R.id.myIdTag)
return myFragmentView;
}
upvote
  flag
There's no reason for the field. You can always call getView() later – cricket_007

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);
    }
}
upvote
  flag
Yes, this code here is okay. Your edits to the other are not. – cricket_007
upvote
  flag
@cricket_007 ok which one can you saw me? – RobbyPatel
upvote
  flag
I'm sorry I can't quite understand your English, but everything is fixed now. I have nothing to show you. – cricket_007

The easiest way to use such things is to use butterknife By this you can add as many Onclciklisteners just by @OnClick() as described below:

public class TestClass extends Fragment {
    @BindView(R.id.my_image) ImageView imageView;
    @OnClick(R.id.my_image)
    public void my_image_click(){
        yourMethod();
    }
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View view=inflater.inflate(R.layout.testclassfragment, container, false);
        ButterKnife.bind(getActivity,view);
        return view;
    }
}
upvote
  flag
Why down voted, if you use this, you can use multiple onclicks also in on statement. – Amit
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
     View view = inflater.inflate(R.layout.testclassfragment, container, false);
     ImageView imageView = (ImageView) view.findViewById(R.id.my_image);
     return view;
}

Notice if you use getView() method it might cause nullPointerException because it returns the rootview and it will be some view after onCreateView() method.

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;
        }
    }
upvote
  flag
1) What does this add to other answers? 2) You seem to have answered twice – cricket_007

Layout inflater comes into picture here. Layout inflater is a class that make us able to use the XML views in java code. So you can inflate the root xml view in variable v with the following code. And then using v, you can find the child views of the root view v.

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;
    }
}

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;
}
1 upvote
  flag
Without casting thing explained helped me. – shaurya uppal

Not the answer you're looking for? Browse other questions tagged or ask your own question.