How does one create Buttons with Equal Widths?

前端 未结 7 1533
梦如初夏
梦如初夏 2020-12-08 15:07

I want to display three buttons in the middle of a screen, and have the three buttons all be the same width, though they will have text labels of different lengths.

相关标签:
7条回答
  • 2020-12-08 16:03

    Just one additional note from my side!

    If you will need to set the width (or height) for the buttons (or any other views with a simple changes of code) that are added at runtime, you can use the code below (it does not depend on orientation):

    public void AlignButtons(){
        llModules = (LinearLayout) findViewById(R.id.llModules);
    
        ViewTreeObserver viewTree = llModules.getViewTreeObserver();
        viewTree.addOnPreDrawListener(new ViewTreeObserver.OnPreDrawListener() {
            public boolean onPreDraw() {
    
                int childcount = llModules.getChildCount();
                int maxWidth = 0; //int maxHeight = 0;
    
                String fontPath = "fonts/Isabella-Decor.ttf";
                Typeface tf = Typeface.createFromAsset(getAssets(), fontPath);
    
                for (int i = 0; i < childcount; i++) {
                    LinearLayout v = (LinearLayout)llModules.getChildAt(i);
                    View vv = v.getChildAt(0);
                    if (vv instanceof Button) {
                        int width = vv.getMeasuredWidth();
                        maxWidth = (maxWidth > width) ? maxWidth : width;
                        //int height = vv.getMeasuredHeight();
                        //maxHeight = (maxHeight > height) ? maxHeight : height;
                    }
                }
                for (int i = 0; i < childcount; i++) {
                    LinearLayout v = (LinearLayout)llModules.getChildAt(i);
                    View vv = v.getChildAt(0);
                    if (vv instanceof Button) {
                        LayoutParams params = ((Button) vv).getLayoutParams();
                        params.width = maxWidth;
                        //params.height = maxHeight;
                        ((Button) vv).setLayoutParams(params);
    
                        // Applying font
                        ((Button) vv).setTypeface(tf);
                    }
                    vv = v.getChildAt(1);
                    if (vv instanceof TextView) {
                        // Applying font
                        ((TextView) vv).setTypeface(tf);
                    }
                }
    
                return true;
            }
        });
    }
    

    Here, in my case:

    llModule - some layout containing another layout with what we need to align(v.getChildAt(0);) and other(v.getChildAt(1);).

    LinearLayout v = (LinearLayout)llModules.getChildAt(i); - obtain layout of buttons to align.

    Other parts are clear to understand.

    Two cycles in this code are quite identical, but I still can't imagine how to combine them (to speed up the execution time).

    0 讨论(0)
提交回复
热议问题