简体   繁体   English

ListView findViewById返回null

[英]ListView findViewById returning null

I'm not using a ListActivity because I want to extend FragmentActivity. 我没有使用ListActivity,因为我想扩展FragmentActivity。 Instead I'm trying to use: 相反,我正在尝试使用:

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

Unfortunately lv is null. 不幸的是lv是null。

In my xml I have: 在我的xml中,我有:

 <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. 我也尝试使用不同的android id作为列表视图,例如你在使用ListActivity时必须使用的那个,但它总是空的。

Edit: I was trying to call findViewById before calling setContentView. 编辑:我在调用setContentView之前尝试调用findViewById。 Calling setContentView first fixed it. 调用setContentView首先修复它。

正如JRaymond之前在评论中提到的那样,我需要在使用findViewById之前调用setContentView。

您应该将setContentView放在findViewById之上。

尝试:

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

this may helps you 这可能对你有所帮助

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

remove it from your Listview in xml and use like 从xml中的Listview中删除它并使用like

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM