2010-08-11 186 views
5

我想創建一個帶有提交按鈕的輸入框。在他們之間,他們應該跨越屏幕的寬度。目前,我有:LinearLayout從右到左填充

LinearLayout row= new LinearLayout(context); 
row.setOrientation(HORIZONTAL); 
row.setGravity(Gravity.RIGHT); 
EditText input = new EditText(context); 
Button submit = new Button(context); 
submit.setText("Submit"); 
row.addView(submit); 
row.addView(input,LayoutParams.FILL_PARENT,LayoutParams.WRAP_CONTENT); 
myView.addView(row,LayoutParams.FILL_PARENT,LayoutParams.WRAP_CONTENT); 

這導致正確的空間分佈:提交按鈕佔據儘可能多的空間,因爲它需要的輸入按鈕佔用的剩餘空間,但是他們是南轅北轍(中提交按鈕在左側,儘管設置了重力)。如果我消除重力,並將元素添加到行的順序相反,則輸入框將佔用屏幕的整個寬度,並且提交按鈕不可見。我究竟做錯了什麼?

回答

4

我說,最好是使用相對佈局和放置輸入到按鈕的左側。但如果你真的需要這個線性佈局,可以只使用重量參數:

LinearLayout row= new LinearLayout(context); 
    EditText input = new EditText(context); 
    Button submit = new Button(context); 
    submit.setText("Submit"); 
    LayoutParams inputParams = new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT); 
    inputParams.weight = 1; 
    row.addView(input,inputParams); 
    LayoutParams buttonParams = new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT); 
    buttonParams.weight = 0; 
    row.addView(submit, buttonParams); 
+1

是的,我認爲從代碼形式佈局是不好的主意。所以,只有在xml佈局絕對不適用於你的情況下才能做到這一點。 – 2010-08-11 19:50:03

+0

我對Android還比較陌生,到目前爲止,這個項目中的所有內容都是基於代碼的。我將在未來的項目中使用xml,但現在我將採用代碼解決方案。 – fredley 2010-08-12 08:41:42

0

項目按您添加它們的順序堆疊在LinearLayout中。切換你的兩個addView調用。

它通常更容易實現佈局xml文件的正確佈局。即:

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" 
    android:orientation="horizontal" 
    android:layout_width="fill_parent" 
    android:layout_height="fill_parent"> 
    <EditText 
      android:layout_width="fill_parent" 
      android:layout_height="wrap_content"/> 

    <Button 
      android:layout_width="wrap_content" 
      android:layout_height="wrap_content"/> 
</LinearLayout> 
+0

嗯。這似乎是反直覺,我應該設置重力是正確的,然後事情應該從左邊堆疊。好吧。 – fredley 2010-08-11 19:24:44

+0

這不是什麼引力的意思:http://developer.android.com/reference/android/view/Gravity.html – 2010-08-11 20:25:25

3

嘗試增加EditText設置其寬度fill parent,其重量爲1,那麼該按鈕(寬度= wrap content

0

如果您還需要排隊按鈕的下一行,你也可以使用一個TableLayout。查看代碼示例的apidemos。