在Android中使GridLayout表现得像普通的Java

时间:2014-09-11 14:44:39

标签: java android

我正在编写一个包含GridLayout的Android应用。我没有使用XML,因为它将是一个动态UI随用户输入而改变所以我需要动态添加和删除组件。在这种情况下,我将按钮放在网格布局上,我希望网格中的按钮跨越整个。

在普通的Java中我会像这样写

public class Grids extends JFrame
{
    public static void main(String[] args)
    {
        Grids g=new Grids();
        g.setVisible(true);
    }

    public Grids()
    {
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setBounds(500, 300, 240, 400);

        setLayout(new GridLayout(3,2));
        add(new JButton("A"));
        add(new JButton("B"));
        add(new JButton("C"));
        add(new JButton("D"));
        add(new JButton("E"));
        //add(new JButton("6"));
    }
}

据我所知,这是为Android编写它的方式

public class MainActivity extends Activity
{
    private GridLayout root;
    private Button a, b, c, d, e;

    @Override
    protected void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);

        root = new GridLayout(this);
        root.setRowCount(3);
        root.setColumnCount(2);

        a=new Button(this);
        b=new Button(this);
        c=new Button(this);
        d=new Button(this);
        e=new Button(this);

        a.setText("A");
        b.setText("B");
        c.setText("C");
        d.setText("D");
        e.setText("E");

        root.addView(a);
        root.addView(b);
        root.addView(c);
        root.addView(d);
        root.addView(e);

        this.setContentView(root);
    }
}

但它不像我预期的那样工作。下图说明了我的问题。我需要Android中的按钮来覆盖整个手机屏幕。这个用户界面即时更改,因此在这种情况下,我认为不使用XML会更好。

图片链接

enter image description here

我不允许发布图片,所以你需要手动打开它。

1 个答案:

答案 0 :(得分:0)

您必须在gridView和按钮视图中使用fill_parent。

默认情况下,您有wrap_content - 您可以在屏幕截图中看到的内容。

不可能像这样使用smth:

setBounds(500, 300, 240, 400);

因为您不了解物理设备的尺寸,并且您无法在窗口模式下正常运行应用程序。