【问题标题】:Can not get element from layout无法从布局中获取元素
【发布时间】:2011-02-04 12:54:26
【问题描述】:

我有 2 项活动。第二个 .xml 看起来像:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    >
    <ListView 
            android:id="@+id/TrainsListView"
            android:layout_width="fill_parent"
            android:layout_height="fill_parent" 
        />
</LinearLayout>

清单的一部分:

<activity android:name="TrainsActivity">

</activity>

我正在尝试获取 TrainsListView:

mListView = (ListView) findViewById(R.id.TrainsListView);

但在此之后 mlistView 为空。为什么?

【问题讨论】:

  • 我想知道你是否在你的Activity类中扩展了ListActivity或Activity。

标签: android layout android-layout android-intent


【解决方案1】:

我猜这发生在您的 Activity 的 onCreate() 方法中,因为您在调用 setContentView() 之前调用了 findViewById()。如果不是这种情况,请显示更多您的代码。

【讨论】:

    【解决方案2】:

    如果findViewById() 未能找到您的目标ID,可能会出现以下原因:

    [[在你的情况下,我怀疑#1或#2。]

    1. 尚未调用SetContentView()(或inflate)来关联要搜索的布局。

    2. SetContentView()(或inflate)使用不包含目标 id 的布局调用,例如你指定了错误的布局。

    3. 布局或代码中的id 有错字。

    4. 您导入了错误的R 文件(如库组件的R 文件),巧合的是,另一个R 文件中也使用了相同的ID。

    5. 您正在搜索错误的视图,例如您膨胀了一个菜单布局并且没有将其附加到根布局,然后当您打算搜索膨胀的菜单布局 (menu.findBiewById(..)) 时,您尝试在根布局 (findBiewById(..)) 中搜索一个 id。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-11-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-03-13
      相关资源
      最近更新 更多