【发布时间】:2023-03-10 22:44:01
【问题描述】:
我在布局文件夹main.xml 和hidden.xml 中有两个xml 文件。在我的活动中,内容视图使用setcontentview 设置为main.xml。我想要做的是,当按下某个按钮时,用hidden.xml 给main.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