当模拟器处于水平位置时,动态创建的GridLayout方向不起作用

时间:2019-01-16 18:24:29

标签: java android

我正在动态创建带有9个按钮的GridLayout。但是,当我将模拟器更改为水平位置时,为此GridLayout设置的水平方向不起作用。这是我的代码-

import android.os.Bundle;
import android.app.Activity;
import android.view.Gravity;
import android.view.Menu;
import android.view.View;
import android.view.ViewGroup.LayoutParams;
import android.widget.Button;
import android.widget.GridLayout;
import android.widget.TableRow;
import android.widget.TextView;
import android.widget.Toast;

import static android.view.ViewGroup.LayoutParams.WRAP_CONTENT;

public class MainActivity extends Activity {

    GridLayout gl;
    Button[] buttons;
    int item;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        gl = new GridLayout(MainActivity.this);
        gl.setLayoutParams(new LayoutParams
                (LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT));
        gl.setOrientation(GridLayout.HORIZONTAL);
        gl.setColumnCount(3);
        gl.setRowCount(3);

        buttons = new Button[9];

        for(int i=0;i<9;i++)
        {
            buttons[i] = new Button(MainActivity.this);
            LayoutParams params = new TableRow.LayoutParams(WRAP_CONTENT, WRAP_CONTENT,1f);
            buttons[i].setLayoutParams(params);
            buttons[i].setHeight(WRAP_CONTENT);
            buttons[i].setWidth(WRAP_CONTENT);
            buttons[i].setGravity(Gravity.CENTER);
            buttons[i].setId(i+1);
            int s = buttons[i].getId();
            buttons[i].setText(Integer.toString(s));
            buttons[i].setTextSize(25);
            buttons[i].setWidth(352);
            buttons[i].setHeight(552);
            buttons[i].setPadding(50,50,50,50);
            gl.addView(buttons[i]);
        }

        setContentView(gl);

    }
}

由于我没有使用activity_main.xml创建GridLayout,所以无法在XML中设置方向。因此,在

的MainActivity.java中进行设置

gl.setOrientation(GridLayout.HORIZONTAL);

对于每个动态创建的按钮,我也无法设置layout_gravity来填充。因此,这样做-

buttons[i].setGravity(Gravity.CENTER);

0 个答案:

没有答案