【问题标题】:Android create four buttons with even weight distribution programmaticallyAndroid以编程方式创建四个重量分布均匀的按钮
【发布时间】:2013-04-13 02:04:40
【问题描述】:

我在让我的程序正确显示 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);
    }

【问题讨论】:

  • 你为什么不使用 xml 呢?
  • 尝试做一些不同的事情。我已经知道如何使用 XML 来实现,但我想以编程方式为我正在开发的应用程序进行布局,这需要一些动态布局的东西。

标签: android


【解决方案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);

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

【讨论】:

  • 只是一个参考,获取显示宽度和高度取自这个 SO 线程stackoverflow.com/questions/2902640/…(所以我不知道它是否真的有效)
  • 这是一个不推荐使用的方法,这是否意味着它将在未来的版本中删除?
  • 是的,这确实意味着,查看 android 开发页面,我确信他们已经实现了一种新的方法来实现相同的功能(这只是一个示例)......显示的宽度将每个按钮设置为宽度的 1/4
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2022-01-08
  • 2014-08-11
  • 2014-10-16
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多