日々精進

新しく学んだことを書き留めていきます

CustomViewのlayout xmlにmergeタグを使うとレイアウトが崩れる問題

状況は以下

  • CustomView(名前はPositionView_)のlayout xmlのRootタグはmergeタグ
<merge xmlns:android="http://schemas.android.com/apk/res/android"
       xmlns:tools="http://schemas.android.com/tools"
       android:orientation="vertical"
       android:layout_width="match_parent"
       android:layout_height="wrap_content"
    >
    ...
</merge>
  • Fragmentのlayout xmlは以下。
<ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
            android:layout_width="match_parent"
            android:layout_height="wrap_content">
    ...
        <jp.co.sample.PositionView_
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:visibility="gone"/>
    ...
</ScrollView>

原因はmergeタグを使った場合、mergeタグのattributeはすべて無視されて親のxmlに書いたattributeが使われるため「android:orientation="vertical"」が無効になってしまうため。 FragmentのXMLを以下のようにすると直った。

        <jp.co.sample.PositionView_
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:orientation="vertical"
            android:visibility="gone"/>

でもorientationは親画面が何でも変わらないからCustomViewのXMLの方に書きたいなぁ。CustomViewのattributeに親画面で定義したattributeを上書きして適用するのがいいんだけど。。