Android以编程方式创建四个按钮,均匀分布

时间:2013-04-13 02:04:40

标签: android

我遇到了一些重大问题,让我的程序正确显示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);
    }

1 个答案:

答案 0 :(得分: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);

并为每个按钮执行此操作...相同的宽度在任何大小的屏幕分辨率上均可动态完成!