Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Android fragment - findViewById returns null [duplicate]

I have a problem that seems to be quite common on the internet : I have created an activity with just a fragment. This is the generated code:

@Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_customer);
        if (savedInstanceState == null) {
            getFragmentManager().beginTransaction()
                .add(R.id.container, new PlaceholderFragment()).commit();
            ListView lv = (ListView) findViewById(android.R.id.list);
        }
    }

After or inside the condition, I can't get any object with findViewById: it is always null. Here is the rest of the generated code :

public static class PlaceholderFragment extends Fragment {

    public PlaceholderFragment() {
    }

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

activity_customer.xml:

<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/container"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context="com.axacs.marc.CustomerActivity"
    tools:ignore="MergeRootFrame" />

the listview is actually in fragment_customer.xml:

<ListView
    android:id="@android:id/list"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_below="@+id/new_folder_button"
    android:text="" />

Does anyone know what is missing ?

like image 370
Charline Avatar asked Jul 24 '14 09:07

Charline


People also ask

Why is findViewById returning NULL?

FindViewById can be null if you call the wrong super constructor in a custom view. The ID tag is part of attrs, so if you ignore attrs, you delete the ID.

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.

What does findViewById return?

findViewById returns an instance of View , which is then cast to the target class. All good so far. To setup the view, findViewById constructs an AttributeSet from the parameters in the associated XML declaration which it passes to the constructor of View . We then cast the View instance to Button .


1 Answers

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);
like image 137
Anirudh Sharma Avatar answered Sep 24 '22 08:09

Anirudh Sharma