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.
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).