android膨胀视图findViewById不起作用

时间:2014-11-23 08:39:20

标签: android

inflate我遇到了大问题而且累了。

我的应用中有另一个布局,message

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

    <TextView
            android:layout_width="match_parent"
            android:layout_height="369dp"
            android:text="New Text"
            android:id="@+id/msg"/>
    <Button
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:text="New Button"
            android:id="@+id/button"/>
    <Button
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:text="New Button"
            android:id="@+id/button2"/>
</LinearLayout>

当我尝试更改msg文字时失败:

View vw = getLayoutInflater().inflate(R.layout.message, null);

msg = (TextView) vw.findViewById(R.id.msg);

msg.setText("123");

setContentView(R.layout.message);

并且应用程序也不例外。

我该如何解决?

2 个答案:

答案 0 :(得分:1)

您必须使用新视图setContentView通过:

setContentView(vw);

答案 1 :(得分:1)

如果它的片段你必须返回vw作为你的观点。

Return vw;

如果是活动,则必须将vw设置为内容视图。

setContentView(vw);