【问题标题】:ListView findViewById returning nullListView findViewById 返回 null
【发布时间】:2012-09-17 23:29:23
【问题描述】:

我没有使用 ListActivity,因为我想扩展 FragmentActivity。相反,我正在尝试使用:

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

不幸的是 lv 为空。

在我的 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>

我也尝试为列表视图使用不同的 android id,例如在使用 ListActivity 时必须使用的那个,但它始终为 Null。

编辑:我在调用 setContentView 之前尝试调用 findViewById。首先调用 setContentView 修复它。

【问题讨论】:

  • 你能展示你的整个布局吗?
  • 你是在打电话给setContentView()之前打电话吗?
  • 请提供完整的活动代码
  • @Andy 如果您在setContentView() 之后调用,请尝试清理/构建并重新启动 Eclipse。
  • 嗨 JRaymond,我在调用 setContentView 之前尝试使用 findViewById。如果您想添加答案,我会接受。下次我会提供更多代码。

标签: android listview android-listview


【解决方案1】:

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

【讨论】:

    【解决方案2】:

    您应该将setContentView 放在findViewById 之上。

    【讨论】:

      【解决方案3】:

      试试:

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

      【讨论】:

        【解决方案4】:

        这可能对你有帮助

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

        从你的 xml 列表视图中删除它并像这样使用

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

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2011-03-16
          • 1970-01-01
          相关资源
          最近更新 更多