要将一个子视图在GridLayout中居中,可以使用以下方法:
<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 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 gridLayout = findViewById(R.id.grid_layout); TextView textView = findViewById(R.id.text_view); gridLayout.setGravity(Gravity.CENTER); 请注意,以上方法对GridLayout中的所有子视图都会产生居中效果。如果只想让特定的子视图居中,可以将它们放置在一个单独的布局容器中,然后使用上述方法将该布局容器居中。