ListView findViewById returning null

允我心安 提交于 2021-01-27 14:20:55

问题


I'm not using a ListActivity because I want to extend FragmentActivity. Instead I'm trying to use:

ListView lv = (ListView) findViewById(R.id.mainListView);

Unfortunately lv is null.

In my xml I have:

 <ListView
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/mainListView"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:layout_weight="1" >
</ListView>

I've also tried using different android id's for the list view such as the one you have to use when you use ListActivity, but it's always Null.

Edit: I was trying to call findViewById before calling setContentView. Calling setContentView first fixed it.


回答1:


As JRaymond mentioned in a comment awhile ago, I needed to call setContentView before using findViewById.




回答2:


You should put setContentView on top of findViewById.




回答3:


Try:

ListView lv = (ListView) view.findViewById(R.id.mainListView);



回答4:


this may helps you

 xmlns:android="http://schemas.android.com/apk/res/android"

remove it from your Listview in xml and use like

<ListView
    android:id="@+id/mainListView"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:layout_weight="1" >
</ListView>


来源:https://stackoverflow.com/questions/12468473/listview-findviewbyid-returning-null

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!