By simplified.


2011-06-27 16:24:47 8 Comments

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 comments

@Vipul Prajapati 2019-06-13 04:15:29

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

@Vivek 2019-12-01 23:04:28

excellent worked well ! thanks a lot

@SwiftArchitect 2018-11-06 03:10:47

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

@Vivek 2019-12-01 22:59:30

no it is returning a error! unreachable code

@friiky 2013-10-09 23:22:03

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.

@priti 2018-01-30 09:51:02

1) first inflate layout of Fragment then you can use findviewbyId .

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

@Novo Lucas 2017-10-08 14:53:05

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

@shaurya uppal 2017-11-03 21:20:30

Without casting thing explained helped me.

@advantej 2011-06-27 16:34:19

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 .

@Dmitry Zaytsev 2012-01-14 19:58:49

Note: it's works only after onCreateView(). So, you can't use this in onCreate()

@Nico AD 2012-07-24 11:47:52

so what is the function I can override to implement this if onCreate is not the right place ?

@MattJenko 2013-04-11 10:48:33

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

@advantej 2013-07-11 15:20:32

The best place to do this the onViewCreated method

@Jon 2014-01-12 14:43:59

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.

@Monstieur 2014-06-05 15:15:40

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.

@jj_ 2015-01-31 23:07:31

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() ???

@Confuse 2015-05-30 12:04:11

getView might return null. LeffelMania has a better solution.

@Muhammad Babar 2016-08-04 10:41:30

@Locutus You must clean up these stored references by setting them back to null in onDestroyView() or you will leak the Activity reference please?

@Bipin Bharti 2017-06-11 20:07:34

@cricket_007 getview work in onCreateview() in fragment

@cricket_007 2017-06-11 20:07:59

@RobbyPatel There's no possible way it can. It will return null.

@Bipin Bharti 2017-06-11 20:14:16

@cricket_007 here is another issue my code is completely good

@Pulak 2017-06-15 13:07:52

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

@cricket_007 2017-06-18 03:03:45

@NoLuck, Yes, but that's what the other answers are for

@Hendy Irawan 2018-01-13 07:00:01

@user3294126 2018-03-28 17:18:49

What if part of creating my Activity (onCreate()) that contains my Fragment depends on the UI elements of the Fragment? Where can I initialize my Fragment's views so that they are initialized after the Fragment has been committed but before the Activity's onCreate() is finished? Or instead should I be initializing my Activity's UI in a method after onCreate(), like onResume()?

@Benjamin Kershner 2019-12-09 22:03:15

Good information on the difference between onViewCreated and onCreateView here: stackoverflow.com/a/38718205/7715734

@Wijay Sharma 2017-07-28 19:56:45

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

@Ankur Chaudhary 2014-03-04 14:46:21

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

@Sonny 2014-10-08 22:11:28

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.

@dVaffection 2015-08-28 04:20:45

Using view passed to onViewCreated still causes NullPointerException but using getActivity() is fine. Any ideas why?

@Ankur Chaudhary 2015-08-28 09:08:33

@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.

@dVaffection 2015-09-04 02:12:50

@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?

@Ankur Chaudhary 2015-09-04 04:55:22

@dVaffection can you please share your class of fragment and corresponding layout.

@dVaffection 2015-09-04 17:29:53

@dVaffection 2015-09-04 17:31:18

In particular ListActivityFragment.java line 63 (FloatingActionButton) getActivity().findViewById(R.id.floating_new_item);

@Ankur Chaudhary 2015-09-11 12:14:56

@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.

@dVaffection 2015-09-12 05:03:48

@AnkurChaudhary What you're saying is valid if you inherit from Fragment, in my case I extend ListFragment which actually returns FrameLayout.

@Ankur Chaudhary 2015-09-24 04:31:39

@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.

@Bipin Bharti 2016-12-08 09:11:17

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

@cricket_007 2017-06-11 20:15:44

Yes, this code here is okay. Your edits to the other are not.

@Bipin Bharti 2017-06-11 20:17:12

@cricket_007 ok which one can you saw me?

@cricket_007 2017-06-11 20:18:32

I'm sorry I can't quite understand your English, but everything is fixed now. I have nothing to show you.

@Mayank Garg 2017-06-06 09:26:57

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

@cricket_007 2017-06-08 12:09:30

1) What does this add to other answers? 2) You seem to have answered twice

@Mahdi-Malv 2017-03-06 22:24:57

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.

@Amit 2017-01-13 10:16:44

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

@Amit 2017-02-01 09:50:28

Why down voted, if you use this, you can use multiple onclicks also in on statement.

@Ramkumar.M 2016-05-20 12:47:01

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

@cricket_007 2017-06-08 12:14:31

There's no reason for the field. You can always call getView() later

@AbhayBohra 2016-04-29 04:51:11

Try This:

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

return v;

@Raja Jawahar 2015-12-31 07:57:39

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

@Nanda Gopal 2016-02-01 19:08:20

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

@Surajit Mondal 2016-05-20 12:45:01

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

@sandhu 2014-12-20 13:03:01

EditText name = (EditText) getView().findViewById(R.id.editText1);
EditText add = (EditText) getView().findViewById(R.id.editText2);  

@Pajeh 2013-05-29 16:35:53

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

@sagits 2014-03-30 01:02:05

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

@Lez 2012-03-28 15:58:13

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

@Devendra Kulkarni 2015-12-06 18:46:30

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;

@Reti43 2015-12-06 19:10:14

This is identical to LeffelMania's answer.

@LeffelMania 2011-06-27 16:35:34

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

@Raunak 2011-10-02 00:33:44

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?

@LeffelMania 2011-10-14 06:18:52

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.

@Nimesh Madhavan 2014-02-16 16:52:19

Note that findViewById has to be called on the view that is inflated, not on getView()

@MrAsterisco 2014-09-12 17:05:18

For future readers: this method does not work. It just raises a android.view.ViewRootImpl$CalledFromWrongThreadException.

@LeffelMania 2014-09-13 18:58:24

Looks like there's something wrong in your code (updating UI from a background thread), not mine.

@altumano 2014-10-12 12:09:43

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.

@Machado 2015-02-19 16:09:43

This should be the right answer. The accepted one leaves you with NullPointerException.

@George 2015-09-25 01:49:35

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

@Aleksey Khivrenko 2016-03-25 19:46:12

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

@KMC 2017-02-24 05:10:49

@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.

@pintergabor 2019-05-02 04:11:25

Casting to ImageView is redundant.

@GW.G 2015-04-24 09:50:23

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 !

@Manoj ahirwar 2015-03-29 08:53:56

Use

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

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

it will work

@Ilya Gazman 2015-01-23 22:57:18

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.

@Mahmoud Badri 2013-07-11 11:55:08

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

@Steve M 2013-09-25 02:24:24

the view is not the activity

@dreamdeveloper 2014-09-03 12:41:44

getView() will give the root view

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

@Dexter 2014-10-13 02:02:18

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

@Michele La Ferla 2014-08-28 12:11:27

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

@Mike Brian Olivera 2014-12-31 04:24:09

i thinked this could be posiible, but , it didn't work

Related Questions

Sponsored Content

2 Answered Questions

[SOLVED] ERROR ANDROID STUDIO E/RecyclerView: No adapter attached; skipping layout

1 Answered Questions

Android: NullPointerException while replacing FrameLayout

  • 2013-10-29 21:24:57
  • Karl Morrison
  • 203 View
  • 0 Score
  • 1 Answer
  • Tags:   android

19 Answered Questions

[SOLVED] Update ViewPager dynamically?

4 Answered Questions

[SOLVED] Understanding Fragment's setRetainInstance(boolean)

2 Answered Questions

18 Answered Questions

[SOLVED] Fling gesture detection on grid layout

1 Answered Questions

[SOLVED] null pointer exception with listview.setadapter() in fragment in method oncreateview

  • 2016-03-09 20:40:20
  • AhmedA.Elsalamony
  • 776 View
  • 2 Score
  • 1 Answer
  • Tags:   android

Sponsored Content