1185

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.

Shubhamhackz
  • 7,333
  • 7
  • 50
  • 71
simplified.
  • 11,977
  • 5
  • 17
  • 8
  • Use ButterKnife viewbinding library for android. Also demonstrate how it’s work, how to integrate and use in your android app development to make your development faster. – Shomu Oct 30 '18 at 04:37
  • 'Some' time has passed but you still haven't accepted an answer. Can you select the answer that helped you most so this can be marked as answered? – David3103 Apr 09 '19 at 08:45
  • It is encourages to use Data Binding orang View Binding instead manual findViewById – mochadwi Jan 10 '20 at 11:51

37 Answers37

1599

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 .

Uddhav P. Gautam
  • 7,362
  • 3
  • 47
  • 64
advantej
  • 20,155
  • 4
  • 34
  • 39
  • 338
    Note: it's works only after onCreateView(). So, you can't use this in onCreate() – Dmitry Zaytsev Jan 14 '12 at 19:58
  • 7
    so what is the function I can override to implement this if onCreate is not the right place ? – Nico AD Jul 24 '12 at 11:47
  • 17
    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 Apr 11 '13 at 10:48
  • 25
    The best place to do this the onViewCreated method – advantej Jul 11 '13 at 15:20
  • 1
    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 Jan 12 '14 at 14:43
  • 37
    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 Jun 05 '14 at 15:15
  • 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()` ??? – Redoman Jan 31 '15 at 23:07
  • 1
    `getView` might return null. LeffelMania has a better solution. – Confuse May 30 '15 at 12:04
  • 4
    @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 Aug 04 '16 at 10:41
  • @cricket_007 getview work in onCreateview() in fragment – Bipin Bharti Jun 11 '17 at 20:07
  • 1
    @RobbyPatel There's no possible way it can. It will return null. – OneCricketeer Jun 11 '17 at 20:07
  • @cricket_007 here is another issue my code is completely good – Bipin Bharti Jun 11 '17 at 20:14
  • 1
    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 Jun 15 '17 at 13:07
  • @NoLuck, Yes, but that's what the other answers are for – OneCricketeer Jun 18 '17 at 03:03
  • @MuhammadBabar reference: https://developer.android.com/reference/android/app/Fragment.html – Hendy Irawan Jan 13 '18 at 07:00
  • 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()`? – user3294126 Mar 28 '18 at 17:18
  • Good information on the difference between onViewCreated and onCreateView here: https://stackoverflow.com/a/38718205/7715734 – Benjamin Kershner Dec 09 '19 at 22:03
  • I would recommend using `view.findViewById` since this has a built-in NonNull annotation, thus no warnings to handle null pointer exceptions – Pranav Kasetti Jun 07 '20 at 13:10
  • mine giving null. I have posted a new [question](https://stackoverflow.com/q/67313132/6854117) – Moeez Apr 29 '21 at 07:50
  • Important to note is onViewCreated and NOT onCreateView or else app will crash saying unable to inflate. – Anuj Sep 17 '22 at 21:40
665

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;
}
JJD
  • 50,076
  • 60
  • 203
  • 339
LeffelMania
  • 12,765
  • 4
  • 32
  • 34
  • 4
    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 Oct 02 '11 at 00:33
  • 21
    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 Oct 14 '11 at 06:18
  • Note that findViewById has to be called on the view that is inflated, not on getView() – Nimesh Madhavan Feb 16 '14 at 16:52
  • For future readers: this method does not work. It just raises a android.view.ViewRootImpl$CalledFromWrongThreadException. – MrAsterisco Sep 12 '14 at 17:05
  • 1
    Looks like there's something wrong in your code (updating UI from a background thread), not mine. – LeffelMania Sep 13 '14 at 18:58
  • 1
    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 Oct 12 '14 at 12:09
  • 4
    This should be the right answer. The accepted one leaves you with `NullPointerException`. – Machado Feb 19 '15 at 16:09
  • 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 Sep 25 '15 at 01:49
  • @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 Mar 25 '16 at 19:46
  • @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. – KMC Feb 24 '17 at 05:10
  • Casting to ImageView is redundant. – pintergabor May 02 '19 at 04:11
153

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");
Ankur Chaudhary
  • 2,709
  • 3
  • 19
  • 30
  • 7
    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 Oct 08 '14 at 22:11
  • Using `view` passed to `onViewCreated` still causes `NullPointerException` but using `getActivity()` is fine. Any ideas why? – Dmitry Aug 28 '15 at 04:20
  • @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 Aug 28 '15 at 09:08
  • @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? – Dmitry Sep 04 '15 at 02:12
  • @dVaffection can you please share your class of fragment and corresponding layout. – Ankur Chaudhary Sep 04 '15 at 04:55
  • @AnkurChaudhary You can find it here https://github.com/dVaffection/YAGL/tree/master/app/src/main/java/com/dvlab/yagl – Dmitry Sep 04 '15 at 17:29
  • In particular `ListActivityFragment.java` line 63 `(FloatingActionButton) getActivity().findViewById(R.id.floating_new_item);` – Dmitry Sep 04 '15 at 17:31
  • @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 Sep 11 '15 at 12:14
  • @AnkurChaudhary What you're saying is valid if you inherit from `Fragment`, in my case I extend `ListFragment` which actually returns `FrameLayout`. – Dmitry Sep 12 '15 at 05:03
  • @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 Sep 24 '15 at 04:31
69

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;
    }
}
MattJenko
  • 1,208
  • 8
  • 11
  • 1
    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 Apr 19 '13 at 01:01
  • 1
    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 Oct 15 '13 at 07:05
  • @MattJenko, can you share more details or sample how to do have working solution when the inflated layout is used? for instance, i have an viewpager2 with tablayout (4 tabs ) mediated, and I am inflating the edittext views in fragment, and I need to access the editext for each viewpager2's view from main activity. How to do it exactly? – HX_unbanned Feb 04 '22 at 10:44
54

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;
}
xevincent
  • 3,674
  • 18
  • 20
33

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);
    }
}
Apurv
  • 391
  • 2
  • 9
Vipul Prajapati
  • 1,183
  • 9
  • 11
30

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.

rafvasq
  • 1,512
  • 3
  • 18
  • 48
friiky
  • 426
  • 5
  • 4
21

getView() will give the root view

View v = getView().findViewByID(R.id.x); 
conca
  • 1,394
  • 9
  • 10
dreamdeveloper
  • 1,266
  • 1
  • 15
  • 20
19

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);
    }
}
Community
  • 1
  • 1
Lez
  • 193
  • 1
  • 4
17

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);
}
Ziem
  • 6,579
  • 8
  • 53
  • 86
Renato Probst
  • 5,914
  • 2
  • 42
  • 45
16

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;
priti
  • 892
  • 9
  • 9
12
EditText name = (EditText) getView().findViewById(R.id.editText1);
EditText add = (EditText) getView().findViewById(R.id.editText2);  
Ziem
  • 6,579
  • 8
  • 53
  • 86
sandhu
  • 305
  • 4
  • 4
11

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;
}
Ziem
  • 6,579
  • 8
  • 53
  • 86
Pajeh
  • 704
  • 7
  • 10
11

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;
}
Kartik Shandilya
  • 3,796
  • 5
  • 24
  • 42
10

Use

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

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

it will work

Manoj ahirwar
  • 1,062
  • 1
  • 10
  • 24
9

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

Chris
  • 7,270
  • 19
  • 66
  • 110
Mahmoud Badri
  • 1,256
  • 14
  • 24
9

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;
}
Dexter
  • 566
  • 4
  • 10
9

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);
    }
}
OneCricketeer
  • 179,855
  • 19
  • 132
  • 245
Bipin Bharti
  • 1,034
  • 2
  • 14
  • 27
7
ImageView imageView;
public View onCreateView(LayoutInflater inflater, 
                     ViewGroup container, 
                     Bundle savedInstanceState) {
 View view = inflater.inflate(R.layout.testclassfragment, container, false);
 imageView = view.findViewById(R.id.my_image);
 return view;

}

Rehan Khan
  • 1,031
  • 13
  • 10
6

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);
}
Ziem
  • 6,579
  • 8
  • 53
  • 86
Nanda Gopal
  • 2,519
  • 1
  • 17
  • 25
5

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

Michele La Ferla
  • 6,775
  • 11
  • 53
  • 79
5

Try This:

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

return v;
Ziem
  • 6,579
  • 8
  • 53
  • 86
AbhayBohra
  • 2,047
  • 24
  • 36
5

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;
}
Ramkumar.M
  • 681
  • 6
  • 21
4

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.

Ilya Gazman
  • 31,250
  • 24
  • 137
  • 216
4

I like everything to be structured. You can do in this way.

First initialize view

private ImageView imageView;

Then override OnViewCreated

@Override
    public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        findViews(view);
    }

Then add a void method to find views

private void findViews(View v) {
    imageView = v.findViewById(R.id.img);
}
Vasia Zaretskyi
  • 349
  • 3
  • 9
4
//here you can do it by
   public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState)
  {
    // Inflate the layout for this fragment
    final View view =  inflater.inflate(R.layout.fragment_apple, container, 
 false);
    ist = view.findViewById(R.id.linearLink);
    second = view.findViewById(R.id.linearPhone);
    return view;
Mazhar Iqbal
  • 813
  • 7
  • 7
3

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

mrSurprise
  • 37
  • 4
3

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;
Jorgesys
  • 124,308
  • 23
  • 334
  • 268
3

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);
}
Ziem
  • 6,579
  • 8
  • 53
  • 86
Raja Jawahar
  • 6,742
  • 9
  • 45
  • 56
3

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
}}
Surajit Mondal
  • 182
  • 2
  • 8
3

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;
        }
    }
OneCricketeer
  • 179,855
  • 19
  • 132
  • 245
Mayank Garg
  • 1,284
  • 1
  • 11
  • 23
3

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;
    }
}
help-info.de
  • 6,695
  • 16
  • 39
  • 41
Wijay Sharma
  • 439
  • 7
  • 17
3

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);
}
SwiftArchitect
  • 47,376
  • 28
  • 140
  • 179
2

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
  • 577
  • 5
  • 7
  • Why down voted, if you use this, you can use multiple onclicks also in on statement. – Amit Feb 01 '17 at 09:50
2

Very simple way to do:

 @Nullable
        @Override
        public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
            View fragmentView = inflater.inflate(R.layout.testclassfragment, container, false);
            ImageView imageView = (ImageView)fragmentView.findViewById(R.id.my_image);
            return fragmentView;
       }
Ganesh
  • 923
  • 1
  • 7
  • 12
1
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.

Mahdi-Malv
  • 16,677
  • 10
  • 70
  • 117
-2

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 !

Community
  • 1
  • 1
GW.G
  • 11
  • 1