Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/android/234.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Android 使所有按钮在垂直直线上具有相同的宽度_Android_Button_Width - Fatal编程技术网

Android 使所有按钮在垂直直线上具有相同的宽度

Android 使所有按钮在垂直直线上具有相同的宽度,android,button,width,Android,Button,Width,我试图使一条水平线中的所有按钮都具有相同的宽度,基于一个包含最长文本的按钮。 我尝试的是通过布局中的所有按钮,并将其设置为这样的大小 LinearLayout layout = (LinearLayout) findViewById(R.id.buttonLayout); for(int i = 0;i < layout.getChildCount();i++){ View v = layout.getChildAt(i); if(v instan

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

我尝试的是通过布局中的所有按钮,并将其设置为这样的大小

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());
            }
        }
    }
LinearLayout布局=(LinearLayout)findViewById(R.id.buttonLayout);
对于(int i=0;i
这确实设置了所有按钮的大小,但是,所设置的大小不是
宽按钮的大小,而是大约40%


我是如何做到这一点的?

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

问题是,我在ActivitysOnCreate上调用了这段代码。 目前,尚未计算按钮的大小

因此我找到了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());
                    }
                }
            }
        }
    });
final LinearLayout layout=(LinearLayout)findViewById(R.id.buttonLayout);
ViewTreeObserver vto=layout.getViewTreeObserver();
vto.addOnGlobalLayoutListener(新的ViewTreeObserver.OnGlobalLayoutListener(){
@凌驾
公共图书馆{
layout.getViewTreeObserver().removeOnGlobalLayoutListener(此);
对于(int i=0;i

这很好。

如果你解决了问题,你可以发布答案和解决方案并接受。这就是我尝试的。给我的是:声誉低于10的用户在提问后8小时内无法回答自己的问题。您可以回答2014年4月7日上午4:11:28。在此之前,请使用评论或编辑您的问题。