简体   繁体   中英

LinearLayout filled from Right to Left

I want to create an input box with a submit button to the right. Between them they should span the width of the screen. Currently I have:

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

This results in the correct distribution of space: The submit button taking up as much space as it needs, the input button taking up the remaining space, however they are the wrong way round (the submit button is on the left, despite setting the gravity). If I take away the gravity, and reverse the order of adding the elements to the row, the input box takes up the whole width of the screen, and the submit button is not visible. What am I doing wrong?

I'd say it is better to use relative layout and place input to left of the button. But if you really need this with Linear layout you can just use weight parameter:

    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

Items stack in a LinearLayout in the order in which you added them. Switch your two addView calls.

Its typically easier to achieve the right layout with the layout xml files. Ie:

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

If you also need to line up buttons on the next line, you can also use a TableLayout. Look at the apidemos for code sample.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM