画竜点睛を衝く@mapyo

日々やった事をつらつらと書くブログです

androidでxmlを使って動的にviewを追加していく時にハマった事

inflateとかいうやつを使えばよい。

infraterって何だ - ニヤリ TechSide  

AndroidでViewをXMLから動的に生成する » tech-tec

こちらの方々の記事を参考に、やろうとしていたが、どうしても、追加させたいレイアウトの一番最初の要素しか追加されなかった。 なぜだー!!!と数日考えてググりまくっていたのだけど、ついに判明して、残念な気持ちになったのでメモしとく。 以下、自分の追加したかったLayout

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="horizontal"
    android:id="@+id/newlayout"
     >
      <TextView
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:text="text2222" >
    </TextView>
    <Button
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:text="test1"
                >
    </Button>
    <Button
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:text="test2"
    android:id="@+id/newBtn2"
                >
    </Button>
</LinearLayout>

何で追加されないのかわけがわからなくなって変数とかめちゃくちゃなんだけど、 原因は、

android:orientation="horizontal"

となっていたからでした。。。 横に要素が追加されていっていたため、一番最初の要素が表示されてそれ移行は見えなくなっていた? 感じだった。。。

android:orientation="vertical"

と変更したら一瞬で解決した。。。残念過ぎるな。。。 コピペした時にこう変わってしまったのだろう。。。

こんな事でハマる人はいないと思うけど、数日無駄な時間を過ごす事のないように気をつけて!!