0

我在让我的程序以相同宽度并排正确显示 4 个按钮时遇到重大问题。我尝试了一堆组合,并在 StackOverflow 搜索解决方案上花费了一个多小时,但其中任何一个都没有运气。如何在垂直界面的同一行中使这四个按钮都具有相同的高度?

这是我到目前为止没有运气的情况。按钮太大、太小或从宽度 0 起被隐藏。

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

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

        Button redButton = new Button(this);
        redButton.setText("Red");
        LinearLayout.LayoutParams p = new LinearLayout.LayoutParams(
                0,
                LayoutParams.WRAP_CONTENT, 
                0.25f);
        redButton.setWidth(0);
        redButton.setLayoutParams(p);
        layout.addView(redButton);

        Button greenButton = new Button(this);
        greenButton.setText("Green");
        greenButton.setLayoutParams(p);
        greenButton.setWidth(0);
        layout.addView(greenButton);

        Button blueButton = new Button(this);
        blueButton.setText("Blue");
        blueButton.setLayoutParams(p);
        blueButton.setWidth(0);
        layout.addView(blueButton);

        Button yellowButton = new Button(this);
        yellowButton.setText("Yellow");
        yellowButton.setLayoutParams(p);
        yellowButton.setWidth(0);
        layout.addView(yellowButton);

        setContentView(layout);
    }
4

1 回答 1

1

使用以下方法获取设备屏幕的分辨率怎么样:

Display d = ((WindowManager)getSystemService(Context.WINDOW_SERVICE)).getDefaultDisplay();
int screen_width = d.getWidth();
int screen_height = d.getHeight();

然后说如果你想要 4 个按钮,每个按钮在屏幕上都具有相同的宽度,从你的例子中调用greenButton.setWidth(screen_width/4);

并为您的每个按钮执行此操作...在任何尺寸的屏幕分辨率上都具有相同的宽度,所有这些都是动态完成的!

于 2013-04-13T02:22:06.413 回答