【问题标题】:Making all Buttons in a vertical LinearLayout the same width使垂直 LinearLayout 中的所有按钮宽度相同
【发布时间】:2014-05-18 22:14:52
【问题描述】:

我试图使一个水平线性布局中的所有按钮具有相同的宽度,基于一个包含最长文本的按钮。

我尝试的是遍历布局中的所有按钮并设置这样的大小。

LinearLayout layout = (LinearLayout) findViewById(R.id.buttonLayout);

    for(int i = 0;i < layout.getChildCount();i++){
        View v = layout.getChildAt(i);
        if(v instanceof Button){
            if(!(v.getId() == R.id.widestButton)){
                ((Button) v).setWidth(findViewById(R.id.widestButton).getWidth());
            }
        }
    }

这确实设置了所有按钮的大小,但是,设置的大小不是widestButton 的大小,大约是它的 40%。

我该如何进行这项工作?

【问题讨论】:

  • 如果你解决了你的问题,你发布一个带有解决方案的答案并接受它。
  • 这是我试过的。给我这个:声誉低于 10 的用户在提问后 8 小时内无法回答自己的问题。您可以在 2014 年 4 月 7 日凌晨 4:11:28 回答。在此之前,请使用 cmets,或编辑您的问题。

标签: android button width


【解决方案1】:

我自己找到了答案,可能通过谷歌搜索找到了。

问题是,我在 Activity onCreate 上调用此代码。 此时,Button 的大小尚未计算。

所以我找到了 ViewTreeObserver,它能够添加一个侦听器,以便在布局加载完成时调用。我现在使用的代码是:

final LinearLayout layout = (LinearLayout) findViewById(R.id.buttonLayout);
    ViewTreeObserver vto = layout.getViewTreeObserver();
    vto.addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
        @Override
        public void onGlobalLayout() {
            layout.getViewTreeObserver().removeOnGlobalLayoutListener(this);
            for(int i = 0;i < layout.getChildCount();i++){
                View v = layout.getChildAt(i);
                if(v instanceof Button){
                    if(!(v.getId() == R.id.widestButton)){
                        ((Button) v).setWidth(findViewById(R.id.widestButton).getWidth());
                    }
                }
            }
        }
    });

效果很好。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-12-07
    • 2015-11-03
    • 2017-06-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多