LinearLayout在动态创建时返回null

时间:2014-05-15 14:55:20

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

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

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

我的问题是,LinearLayout可以使null成为hidden.xml的原因是什么?

JavaCode:

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" />

1 个答案:

答案 0 :(得分:0)

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

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

用这个:

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