i would like to have three buttons taking equal amount of available space horizontally in a row.
I used android:layout_gravity
. What is the problem?
layout
The following layout should work. weights are for LinearLayouts..
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:orientation="horizontal"
android:weightSum="3"
>
<Button android:id="@+id/button1"
...
android:layout_weight="1"/>
<Button android:id="@+id/button2"
...
android:layout_weight="1"/>
<Button
android:id="@+id/button3"
...
android:layout_weight="1"/>
</LinearLayout>
Please consider the following layout snippet:
<LinearLayout
android:orientation="horizontal"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:weightSum="3">
<ImageView
android:src="@drawable/logo1"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1"
android:layout_gravity="left|center_vertical" />
<TextView
android:id="@+id/toolbar_title"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:text="Some Title"
android:textColor="@android:color/black"
android:layout_gravity="center"
android:gravity="center"
android:layout_weight="1" />
<ImageView
android:src="@drawable/logo2"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1"
android:layout_gravity="right|center_vertical" />
</LinearLayout>
2 things to note above.
A. I created a LinearLayout with weightSum of 3.
B. Then inside that I create 3 elements each having layout_weight of 1 so that I can have my child elements distribute the entire space among themselves evenly.
I have make it pragmatically without weight
float width = CommonUtills.getScreenWidth(activity);
int cardWidth = (int) CommonUtills.convertDpToPixel(((width) / 3), activity);
LinearLayout.LayoutParams params =
new LinearLayout.LayoutParams(cardWidth,
LinearLayout.LayoutParams.MATCH_PARENT);
btnOne.setLayoutParams(params);
btnTwo.setLayoutParams(params);
btnThree.setLayoutParams(params);
public class CommonUtills {
public static float getScreenWidth(Context context) {
float width = (float) 360.0;
DisplayMetrics displayMetrics = context.getResources().getDisplayMetrics();
width = displayMetrics.widthPixels / displayMetrics.density;
return width;
}
}
<LinearLayout
android: layout_width = "match_parent"
android: layout_height = "50dp"
android: orientation = "horizontal" >
<Button
android: id = "@+id/btnOne"
android: layout_width = "wrap_content"
android: layout_height = "match_parent" > </Button>
<Button
android: id = "@+id/btnTwo"
android: layout_width = "wrap_content"
android: layout_height = "wrap_content" > </Button>
<Button
android: id = "@+id/btnThree"
android: layout_width = "wrap_content"
android: layout_height = "wrap_content" > </Button>
</LinearLayout>