Findviewbyid Returns Null When Using Fragment

findViewById returns NULL when using Fragment

You should inflate the layout of the fragment on onCreateView method of the Fragment then you can simply access it's elements with findViewById on your Activity.

In this Example my fragment layout is a LinearLayout so I Cast the inflate result to LinearLayout.

    public class FrgResults extends Fragment 
{
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState)
{
//some code
LinearLayout ll = (LinearLayout)inflater.inflate(R.layout.frg_result, container, false);
//some code
return ll;
}
}

findViewById returns null in fragment class

I got it....
I had defined the findViewById in onGetView
I had to declare it on OnCreateView
Sorry.....

Android fragment - findViewById returns null

use following after moving this line to onCreateView() if you want to use your listview in your fragment

ListView lv = (ListView)rootview.findViewById(android.R.id.list);

.findViewById() returns null

Check that the Switch class you imported in your java file is the correct one (e.g. the same one you used in the xml). This often happens with Toolbar (there are at least two, and if you import the wrong one and things don't work right/can't be cast and end up null).

findViewById returns null if used outside OnCreateView

You could save the view that you are inflating from the block

    onCreateView(LayoutInflater inflater, ViewGroup container, 
Bundle savedInstanceState){
//Previous code
view = inflater.inflate(R.layout.article_view, container, false);
}

then you can call it anywhere else in your code to get the view like this:

    view.findViewById(R.id.view_searched);

instead of :

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

findViewById sometimes returns null in fragment

Solved, a fragment-v21.xml file was being loaded instead of fragment.xml.

The v21 one had different code.

findViewByID returns null

which returns null

Possibly because you are calling it too early. Wait until onFinishInflate(). Here is a sample project demonstrating a custom View accessing its contents.

findViewById returning null in fragment

public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle 

savedInstanceState) {
View view = inflater.inflate(R.layout.capture_card_phone_number, container, false);
mPhone = (AutoCompleteTextView) getActivity().findViewById(R.id.phone_number);
Button next = (Button) view.findViewById(R.id.capture_phone_next);
next.setOnClickListener(this);

return view;

You have to call findViewById on your view - not on your activity.



Related Topics



Leave a reply



Submit