2011-02-17 41 views

回答

12

嘗試:

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

感謝那些工作。爲什麼使用dip而不是px? – Somk 2011-02-17 12:41:07

8

可以設置maragin左,mariagn權,如果你曾經使用相對佈局,那麼你可以使用下面的參數 layout_centerInParent,機器人的:layout_centerVertical,機器人:layout_centerHorizo​​ntal

如果要將按鈕置於垂直居中,則使用居中垂直真,或者如果要將居中按鈕置於水平居中,則使用居中水平真 ,如下圖所示

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

傾角是指密度Indepent像素,這意味着,如果您設置的值10,這是相同的所有設備,其中爲PX(像素)取絕對值,所以你的定位可能出錯的一些設備,這就是爲什麼,也使的不是,你可以用蘸作爲DP太多,編譯器轉換DP沾

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>