Androidのグリッド レイアウトで中央揃えする方法は何ですか。
GridLayout に子ビューを中央揃えにするには、以下のようにします。
- GridLayoutのXMLレイアウトファイルで、子ビューのgravity属性をcenterに設定します。
<GridLayout
android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:gravity="center"
android:text="Centered TextView" />
</GridLayout>
- GridLayoutのXMLレイアウトファイルでは、layout_gravity属性でGridLayoutの子ビューをすべて中央に揃えられます。
<GridLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_gravity="center">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Centered TextView" />
</GridLayout>
- GridLayoutのJavaコードにおける、setGravity()メソッドを使用して子ビューを中央に配置します。
GridLayout gridLayout = findViewById(R.id.grid_layout);
TextView textView = findViewById(R.id.text_view);
gridLayout.setGravity(Gravity.CENTER);
上記の方法はGridLayout内のすべての子ビューに中央揃え効果を適用することに注意してください。特定の子ビューのみを中央揃えにする場合は、それらを個別のレイアウトコンテナに配置してから、上記の方法を使用してそのレイアウトコンテナを中央揃えします。