GridLayout中的Gravity.CENTER不起作用

时间:2017-10-02 18:00:15

标签: android

这是运行良好的XML,当我在Android Studio中运行时,如何以编程方式进行此操作?

<?xml version="1.0" encoding="utf-8"?>
<GridLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_gravity="center"
    tools:context="com.test.MainActivity">
        <TextView
            android:text="Texto 1"/>

</GridLayout>

这是我试图取得成功的代码......

//TODO create Grid params
GridLayout.LayoutParams gridParams = new GridLayout.LayoutParams();
gridParams.height = GridLayout.LayoutParams.WRAP_CONTENT;
gridParams.width = GridLayout.LayoutParams.WRAP_CONTENT;
//TODO set gravity to CENTER
gridParams.setGravity(Gravity.CENTER);

//TODO create GridLayout
GridLayout gridLayout = new GridLayout(context);
//TODO set Grid Params
gridLayout.setLayoutParams(gridParams);

//TODO create TextView
TextView textView = new TextView(context);
textView.setText("Text 1");
//TODO add to Grid
gridLayout.addView(textView);

setContentView(gridLayout);

Android Studio版本2.3.3 在运行Android 4.2.2的平板电脑中测试

编辑工作

RelativeLayout.LayoutParams layoutParams =
                    new RelativeLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT,
                            ViewGroup.LayoutParams.MATCH_PARENT);
RelativeLayout parentRelativeLayout = new RelativeLayout(context);
parentRelativeLayout.setLayoutParams(layoutParams);
parentRelativeLayout.setGravity(Gravity.CENTER);
parentRelativeLayout.addView(gridLayout);

2 个答案:

答案 0 :(得分:0)

您的网格布局需要位于另一个布局中,例如RelativeLayout,其宽度和高度匹配父级。

并不是说它不起作用,只要想到这样,gridLayout就足以容纳自己的容器了,这个容器的大小并不大。

答案 1 :(得分:0)

试试这个。

GridLayout.LayoutParams gridParams = new GridLayout.LayoutParams();
gridParams.height = GridLayout.LayoutParams.WRAP_CONTENT;
gridParams.width = GridLayout.LayoutParams.MATCH_PARENT;
params.gravity = Gravity.CENTER;
params.weight=1.0f;

// TODO创建网格参数