Reputation: 12057
How do I center a button and make it so it is 10px off of each side. Basicly 100% wide minus 10px on the left and right.
Upvotes: 3
Views: 16476
Reputation: 12037
You can set maragin left and mariagn right,If you had used Relative Layout then you can make use of the following parameters layout_centerInParent, android:layout_centerVertical, android:layout_centerHorizontal
If you want to center the Button in Vertical then use Center vertical true , or if you want to center Button in Horizontal then use Center Horizontal true as shown i below
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="SignUp Here"
android:id="@+id/mysignup"
android:layout_alignBottom="@+id/mylogin"
android:layout_weight="1"
android:layout_centerInParent="true" <!-- use depending upon your need -->
android:layout_centerVertical="true" <!-- use depending upon your need -->
android:layout_centerHorizontal="true" <!-- use depending upon your need -->
/>
Dip refers to Density Indepent Pixels, this is means, if you had set the value of 10 , it's same for all device, where as px(pixels) takes absolute value, so your alignment may go wrong in some devices, that's why, also make a not of it , you can use dip as dp too, compiler converts dp to dip
Upvotes: 8
Reputation: 1507
First: forget about pixel, always use dp as unit. Do you want to add it programaticaly or via layout xml files?
If you need to add it programaticaly use this:
LinearLayout layout = new LinearLayout(context);
layout.setLayoutParams(new LayoutParams(LayoutParams.FILL_PARENT,
LayoutParams.FILL_PARENT));
Button button = new Button(context);
button.setText("Some label");
LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(LayoutParams.FILL_PARENT,
LayoutParams.FILL_PARENT,
1);
params.setMargins(10, 0, 10, 0);
button.setLayoutParams(params);
layout.addView(button);
If you would like to add it from layout file do like following:
<?xml version="1.0" encoding="utf-8"?><LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:paddingTop="3dp"
android:paddingRight="10dp" android:paddingLeft="10dp"
android:layout_height="fill_parent" android:layout_width="fill_parent">
<Button android:layout_height="fill_parent" android:id="@+id/scroll_story_title"
android:ellipsize="end" android:layout_gravity="center"
android:maxLines="2" android:gravity="center"
android:text="Something to show to the user and that's pretty cool"
android:layout_marginTop="3dp" android:textSize="11sp"
android:layout_width="fill_parent"></Button>
Upvotes: 3
Reputation: 57702
try that:
layout_width="fill_parent"
layout_marginLeft="10dip"
layout_marginRight="10dip"
Upvotes: 12