1

ドキュメントによると<include>、XML リソース ファイルのタグに id を設定すると、含まれているレイアウトのルート ビューの id をオーバーライドする必要があります。しかし、うまくいかないようです。

私はそれを実証するために非常に単純なプロジェクトを作成しました:

activity_main.xml

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <include
        android:id="@+id/test"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        layout="@layout/merge_layout" />

</RelativeLayout>

merge_layout.xml

<merge xmlns:android="http://schemas.android.com/apk/res/android">
    <LinearLayout
        android:layout_width="wrap_content"
        android:layout_height="wrap_content">
        <Button
            android:id="@+id/button"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content" />
    </LinearLayout>
</merge>

これを実行すると:

protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    if (findViewById(R.id.button) == null)
        throw new RuntimeException("button is null"); // Never happens
    if (findViewById(R.id.test) == null)
        throw new RuntimeException("test is null");
}

その後、毎回 2 番目の例外がスローされます。何か不足していますか?

4

2 に答える 2

0

わかりました答えはかなり明白でした。私はどのように<merge>機能するかを誤解していました。このタグは必須だと思っていましたが、そうではありません。その結果、の代わりに がタグにandroid:id適用されました。<merge><LinearLayout>

タグを削除する<merge>と問題が解決しました。

于 2013-07-07T11:45:47.273 に答える