-2

我想用 TableLayout 做一个计算器。我知道它更适合 GridLayout 但 TableLayout 是必须的。

我试图得到这个设计:

在此处输入图像描述

如您所见,数字(1 到 9)的大小和顺序相同,带有连接和断开按钮。然而,在我目前的设计中,它是这样的:

但我设计中的按钮看起来像:

在此处输入图像描述

这是我的代码:

LinearLayout layout = new LinearLayout(this);
layout.setOrientation(LinearLayout.VERTICAL);
layout.setLayoutParams(new LayoutParams(LayoutParams.MATCH_PARENT,LayoutParams.MATCH_PARENT));

TextView titleView = new TextView(this);
titleView.setText("Table Layout");
titleView.setLayoutParams(new LayoutParams(LayoutParams.WRAP_CONTENT,LayoutParams.WRAP_CONTENT));
layout.addView(titleView);


LinearLayout layout2 = new LinearLayout(this);
layout2.setOrientation(LinearLayout.HORIZONTAL);
layout2.setLayoutParams(new LayoutParams(LayoutParams.MATCH_PARENT,LayoutParams.WRAP_CONTENT));




Button btnConnect = new Button(this);
btnConnect.setText("Connect");
btnConnect.setLayoutParams(new LinearLayout.LayoutParams(0, LinearLayout.LayoutParams.WRAP_CONTENT, 1));
layout2.addView(btnConnect);

TextView titleViewSpace = new TextView(this);
titleViewSpace.setLayoutParams(new  LinearLayout.LayoutParams(0, LinearLayout.LayoutParams.WRAP_CONTENT, 1));
layout2.addView(titleViewSpace);


Button btnDisconnect = new Button(this);
btnDisconnect.setText("Disconnect");
btnDisconnect.setLayoutParams(new  LinearLayout.LayoutParams(0,  LinearLayout.LayoutParams.WRAP_CONTENT, 1));
layout2.addView(btnDisconnect);

layout.addView(layout2);

TableLayout tblLayout = new TableLayout(this);
tblLayout.setLayoutParams(new TableLayout.LayoutParams(TableLayout.LayoutParams.MATCH_PARENT,TableLayout.LayoutParams.MATCH_PARENT));
TableRow tblrow = null;


for (int i = 1; i <= 9; i++) {
    if (i % 3 == 1) {
        tblrow = new TableRow(this);
        tblLayout.addView(tblrow);

    }
    Button b = new Button(this);
    b.setText("" + i);
    tblrow.addView(b);
}




TableRow tr = new TableRow(this);
Button btnZero = new Button(this);
btnZero.setText("0");
Button btnHash = new Button(this);
btnHash.setText("#");
Button btnStar = new Button(this);
btnStar.setText("*");


tr.addView(btnZero);
tr.addView(btnHash);
tr.addView(btnStar);


tblLayout.addView(tr);
layout.addView(tblLayout);


setContentView(layout);

为了使我的按钮与连接和断开按钮的顺序和大小相同

我只是在循环中创建按钮时这样做

for (int i = 1; i <= 9; i++) {
        if (i % 3 == 1) {
            tblrow = new TableRow(this);
            tblLayout.addView(tblrow);

        }
        Button b = new Button(this);
        b.setText("" + i);
        b.setLayoutParams(new LayoutParams(0,LayoutParams.WRAP_CONTENT,1));
        tblrow.addView(b);
    }

但是当我把这个LayoutParams:

b.setLayoutParams(new LayoutParams(0,LayoutParams.WRAP_CONTENT,1));

按钮(1 到 9)在屏幕上消失。为什么?我该如何克服这个问题?我怎样才能在同一个屏幕上制作这样的按钮?

4

1 回答 1

0

这就是我所需要的:

tblLayout.setStretchAllColumns(true);
于 2013-03-06T10:51:18.017 回答