【问题标题】:LinearLayout returns null when creating it dynamicallyLinearLayout 在动态创建时返回 null
【发布时间】:2023-03-10 22:44:01
【问题描述】:

我在布局文件夹main.xmlhidden.xml 中有两个xml 文件。在我的活动中,内容视图使用setcontentview 设置为main.xml。我想要做的是,当按下某个按钮时,用hidden.xmlmain.xml 充气。为此,我编写了以下发布的代码。

但问题是,在检查LinearLayout 是否为空时,它会返回空,因为toast 会显示相应的消息。

我的问题是,什么会导致 LinearLayout 成为 null,因为它在 hidden.xml 中可用?

Java代码:

public void onClick(View v) {
        // TODO Auto-generated method stub

        switch (v.getId()) {
        case R.id.addBtn00:
            LinearLayout hiddenLinearLayout = (LinearLayout) findViewById(R.id.hiddenLayout00);
            if (hiddenLinearLayout == null) {
                Toast.makeText(getBaseContext(), "hidden layout is null", Toast.LENGTH_SHORT).show();
            }else {
                LinearLayout myLinearLayout = (LinearLayout) findViewById(R.id.linearLayout01);
                View hiddenInfo = getLayoutInflater().inflate(R.id.hiddenLayout00, myLinearLayout,false);
                myLinearLayout.addView(hiddenInfo);
            }
            //TextView mTv = (TextView) findViewById(R.id.textView00);
            //mTv.setText("This is not the original Text");
            break;

        case R.id.removeBtn00:
            break;

        default:
            break;
        }

hidden.xml:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout 
xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" 
android:layout_width="match_parent"
android:layout_height="match_parent" 
android:id="@+id/hiddenLayout00">
    <TextView 
        android:textAppearance="?android:attr/textAppearanceLarge"
        android:text="This is a Text View" 
        android:layout_height="wrap_content"
        android:id="@+id/textView00" 
        android:layout_width="wrap_content" />

【问题讨论】:

  • 你必须先膨胀布局
  • @user3455363 好的,我遵循了“nikis”的建议,但仍然是 LinearLayout hiddenLinearLayout = (LinearLayout) findViewById(R.id.hiddenLayout00);返回 null?
  • 对于部分 xml,你只是有条件地想要膨胀,最佳实践实际上是使用 ViewStubs developer.android.com/reference/android/view/ViewStub.html

标签: android xml android-layout layout-inflater android-inflate


【解决方案1】:

您以错误的方式膨胀,您应该指向 first 参数处的布局,而不是布局内的 id。替换这个:

getLayoutInflater().inflate(R.id.hiddenLayout00, myLinearLayout,false);

用这个:

getLayoutInflater().inflate(R.layout.hidden, myLinearLayout,false);

【讨论】:

  • 好的,我更正了它,但这是问题的一部分,因为“LinearLayout hiddenLinearLayout = (LinearLayout) findViewById(R.id.hiddenLayout00);”返回空
  • @Elpharaoh 它应该只在第一次返回null
  • @Elpharaoh 也是myLinearLayout 的一部分main.xml
  • 如果您不介意,请再询问一次。你觉得检查 hiddenLinearLayout 是 null 还是没用?
猜你喜欢
  • 1970-01-01
  • 2014-07-19
  • 1970-01-01
  • 2012-03-18
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多