【问题标题】:Android: I can't fetch layout object by its idAndroid:我无法通过 id 获取布局对象
【发布时间】:2012-01-20 21:43:12
【问题描述】:

这是xml代码:

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

这是Java代码:

View mainLayout = findViewById(R.id.mainLayout);
// Or: LinearLayout mainLayout = (LinearLayout)findViewById(R.id.mainLayout);
Log.d("LAYOUT", mainLayout == null ? "NULL" : "NOT NULL"); // Always prints null

布局始终为空。

这是为什么呢? id是正确的,其他元素都可以毫无问题的获取。

【问题讨论】:

  • 必须先膨胀/创建视图,以便 findViewById() 可以访问它。这个视图是可见的(例如显示在一个活动上)还是你需要在这个上下文之外获取它?
  • 不确定,但我认为你必须尝试干净构建你的项目。

标签: java android xml layout


【解决方案1】:

您是否已经使用以下代码将其附加到活动?

setContentView(R.layout.layout_id);

【讨论】:

    【解决方案2】:

    仅当视图当前通过应用程序的setContentView(ID.OF.LAYOUT) 可见时,直接调用findViewById() 才有效。否则,您必须自己膨胀视图。如果你已经有一个视图对象,你可以像这样从中拉出其他视图:

    View v = alreadyInflatedView.findViewById(R.id.idOfChildView);

    编辑:

    如何膨胀视图:

    LayoutInflater inflater =(LayoutInflater)context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
    View v = inflater.inflate(R.layout.idOfViewToInflate, null);
    

    【讨论】:

    • 谢谢!我不知道在获取视图之前我必须调用 setContentView。我的 Android 编程第二天 :)
    【解决方案3】:

    你需要从 xml 设置你的 contentView

    setContentView(R.layout.main); //this will put it on the screen.
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-09-03
      • 1970-01-01
      • 2019-09-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2010-11-26
      • 1970-01-01
      相关资源
      最近更新 更多