簡體   English   中英

LinearLayout從右到左填充

[英]LinearLayout filled from Right to Left

我想在右側創建一個帶有提交按鈕的輸入框。 它們之間應該跨越屏幕的寬度。 目前我有:

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

這導致了正確的空間分布:提交按鈕占用了所需的空間,輸入按鈕占用剩余空間,但是它們是錯誤的方式(提交按鈕在左側,盡管設置了重力)。 如果我取消重力並反轉將元素添加到行的順序,則輸入框占據屏幕的整個寬度,並且提交按鈕不可見。 我究竟做錯了什么?

我想說最好使用相對布局並將輸入放在按鈕的左邊。 但如果你真的需要使用線性布局,你可以使用權重參數:

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

嘗試添加EditText首先將其寬度設置為fill parent ,將其權重fill parent為1,然后按鈕(width = wrap content

項目按照您添加它們的順序堆疊在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>

如果您還需要在下一行上排列按鈕,您還可以使用TableLayout。 查看代碼示例的apidemos。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM