今回はFlameLayoutとLinearLayoutを使ってimageViewとTextViewを組み合わせて一つの
レイアウトとして扱う方法について。
FlameLayoutは、配置されるレイアウトは全て左揃えで表示されます。
FlameLayoutの中に複数のレイアウトを挿入することで重なったレイアウトを
作ることができ、imageViewを使った疑似的なボタンも簡単に作ることができます。
例えば、FrameLayoutの中にLinearLayoutを使って、水平にimageViewを三つ
作りたい時は以下のように作ることが出来ます。
<FrameLayout android:id="@+id/frameLayout1" android:layout_width="match_parent" android:layout_height="120dp"> <LinearLayout android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_marginEnd="20dp" android:layout_marginStart="20dp" android:layout_marginTop="20dp"> <ImageView android:layout_width="0dp" android:layout_height="60dp" android:layout_weight="2" android:background="@drawable/適当な画像"/> <ImageView android:layout_width="0dp" android:layout_height="60dp" android:layout_weight="2" android:layout_marginStart="10dp" android:layout_marginEnd="10dp" android:background="@drawable/適当な画像"/> <ImageView android:layout_width="0dp" android:layout_height="60dp" android:layout_weight="2" android:background="@drawable/適当な画像"/> </LinearLayout> <LinearLayout android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_marginEnd="20dp" android:layout_marginStart="20dp" android:layout_marginTop="55dp"> <TextView android:id="@+id/not_support" android:layout_width="0dp" android:layout_height="60dp" android:layout_weight="2" android:text="仮テキスト" android:textSize="13sp" android:textStyle="bold" android:gravity="center_horizontal" /> <TextView android:id="@+id/supporting" android:layout_width="0dp" android:layout_height="60dp" android:layout_weight="2" android:text="仮テキスト" android:textSize="13sp" android:textStyle="bold" android:layout_marginStart="10dp" android:layout_marginEnd="10dp" android:gravity="center_horizontal"/> <TextView android:id="@+id/supported" android:layout_width="0dp" android:layout_height="60dp" android:layout_weight="2" android:text="仮テキスト" android:textSize="13sp" android:textStyle="bold" android:gravity="center_horizontal"/> </LinearLayout> </FrameLayout>
ポイントは、width=”0dp”とweight=”2″の部分。このようにすることで、親であるFrameLayout内でも
LinearLayoutにおいて設定したパーツを均等に分けることができます。
三つともweight=”2″となっていますが、このweightという
プロパティは、設定したレイアウトをどの割合で表示するかを決める効果を持っています。
例えば、各imageViewをweight=”2″、weight=”5″、weight=”3″とした場合、
二番目のimageViewが一番大きく表示されます。
今回は全部2なので全部同じ大きさ。これをテキストにも同じように設定してあげることで
imageViewと同じ位置に当てはめることができ、一つのレイアウトのように見せることが
できるようになります。
後は、お互いのLinearLayoutでmargin-topで高さを調整して上げれば完成。
蛇足:GridViewでも同じ動きをさせることができますがあちらはサブクラスを作ってonMersureという関数をオーバーライド
して縦横の計算方法を変えないといけないのですごく面倒。同じことするならこっちの方が易しいです。