即使尺寸相同,Button和TextView的大小也不相同

时间:2014-01-02 15:43:36

标签: java android

我想要一个4x TextViews的2x2 GridLayout,如下所示:

TV1  TV2
TV3  TV4

然后我想在TextViews的3个顶部放置3个按钮,这样当绘制完布局时,这就是用户应该看到的内容:

B1   B2
TV3  B3

请注意,所有TextView和Buttons都是相同尺寸的正方形。然后,用户将能够滑动按钮,直到达到所需的图案。因此,如果用户向左滑动B3,则用户将看到:

B1   B2
B3   TV4

但是,当我的布局完成后,这是向用户显示的内容:

enter image description here

以下是代码:

public TextView[] getTList(int level) {
    int iLength = 4;

    TextView[] textviewList = new TextView[iLength];

    for(int i = 0; i < iLength; i++) {
        TextView textview = new TextView(getApplicationContext());
        textview.setId(i + 1);
        textviewList[i] = textview;
        textview.setHeight(buttonDimension);
        textview.setWidth(buttonDimension);
        textview.setGravity(Gravity.CENTER);
        textview.setBackgroundColor(Color.BLUE);
        textview.getBackground().setAlpha(50);
    }

    return textviewList;
}

public Button[] getBList(int level) {
    int iLength = 3;

    Button[] buttonList = new Button[iLength];

    for(int i = 0; i < iLength; i++) {
        Button button = new Button(getApplicationContext());
        button.setId(i + 1);
        button.setText(Integer.toString(i + 1));
        setButton(button);
        buttonList[i] = button;
        button.setHeight(buttonDimension);
        button.setWidth(buttonDimension);
        button.setGravity(Gravity.CENTER);
        button.setBackgroundColor(Color.BLUE);
    }

public void level1() {

    tList = getTList(level);
    bList = getBList(level);

    gameplayGL.setColumnCount(2);
    gameplayGL.setRowCount(2);

    Spec r1 = GridLayout.spec(0);
    Spec r2 = GridLayout.spec(1);
    Spec c1 = GridLayout.spec(0);
    Spec c2 = GridLayout.spec(1);

    GridLayout.LayoutParams t1 = new GridLayout.LayoutParams(r1, c1);
    GridLayout.LayoutParams t2 = new GridLayout.LayoutParams(r1, c2);
    GridLayout.LayoutParams t3 = new GridLayout.LayoutParams(r2, c1);
    GridLayout.LayoutParams t4 = new GridLayout.LayoutParams(r2, c2);

    GridLayout.LayoutParams b1 = new GridLayout.LayoutParams(r1, c1);
    GridLayout.LayoutParams b2 = new GridLayout.LayoutParams(r1, c2);
    GridLayout.LayoutParams b3 = new GridLayout.LayoutParams(r2, c2);

    gameplayGL.addView(tList[0], t1);
    gameplayGL.addView(tList[1], t2);
    gameplayGL.addView(tList[2], t3);
    gameplayGL.addView(tList[3], t4);

    gameplayGL.addView(bList[0], b1);
    gameplayGL.addView(bList[1], b2);
    gameplayGL.addView(bList[2], b3);
}

请注意,按钮不是正方形,而是矩形。此外,TV3似乎是正确的尺寸和我想要的“方形”尺寸。为什么按钮会变形?此外,TV1,TV2和TV4应该与TV3齐平,但我甚至都看不到它们。

1 个答案:

答案 0 :(得分:0)

尝试在所有控件上调用setPadding(0)。如果这不起作用,请尝试使用ImageButton或甚至只使用普通的ImageView代替按钮。另外,buttonDimension是什么?我认为它是match_parent,如果没有尝试的话。