Android/レイアウト/横幅を比率で分割
提供: 初心者エンジニアの簡易メモ
横幅を比率で分割レイアウト
<ScrollView
android:layout_width="match_parent"
android:layout_height="match_parent">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">
<LinearLayout
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_weight="0.7"
android:gravity="center_horizontal"
android:orientation="vertical">
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="hogehoge1" />
</LinearLayout>
<LinearLayout
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_weight="0.3"
android:gravity="center_horizontal"
android:orientation="vertical">
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="hogehoge2" />
</LinearLayout>
</LinearLayout>
</ScrollView>
コードでweightを記述
int WC = ViewGroup.LayoutParams.WRAP_CONTENT; int MP = ViewGroup.LayoutParams.MATCH_PARENT; LinearLayout layout = new LinearLayout(mContext); LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(WC, MP); params.weight = 1.0f; TextView titleView = new TextView(mContext); titleView.setLayoutParams(params); TextView bodyView = new TextView(mContext); bodyView.setLayoutParams(params); TextView extView = new TextView(mContext); extView.setLayoutParams(params); layout.addView(titleView); layout.addView(bodyView); layout.addView(extView);
weightは余白の比率
weightを1:1:1とすると3つとも均等になるが
weightを1:2:1としても、真ん中だけ2倍のサイズにはならない。
残った余白を、それぞれのviewに分け与える比率となる
