Android中心按钮

时间:2011-02-17 12:34:05

标签: android

如何将按钮对中并使其成为每侧10px的按钮。基本上是100%宽,左右为10px。

3 个答案:

答案 0 :(得分:12)

试试:

layout_width="fill_parent"
layout_marginLeft="10dip"
layout_marginRight="10dip"

答案 1 :(得分:8)

你可以设置maragin left和mariagn right,如果你使用了Relative Layout,那么你可以使用以下参数 layout_centerInParent,android:layout_centerVertical,android:layout_centerHorizo​​ntal

如果要将Button置于垂直中心,则使用Center vertical true,或者如果要将Button置于水平中心,则使用Center Horizo​​ntal true 如下图所示

<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指的是Density Indepent Pixels,这意味着,如果你设置了10的值,它对于所有设备都是相同的,其中px(像素)取绝对值,所以你的对齐可能在某些设备中出错,那就是为什么,也不做它,你也可以使用dip作为dp,编译器将dp转换为dip

答案 2 :(得分:3)

首先:忘记像素,始终使用dp作为单位。 你想通过programaticaly或通过布局xml文件添加它吗?

如果你需要添加它programaticaly使用这个:

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

如果您想从布局文件中添加它,请执行以下操作:

<?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>