简体   繁体   English

LinearLayout从右到左填充

[英]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. 项目按照您添加它们的顺序堆叠在LinearLayout中。 Switch your two addView calls. 切换两个addView调用。

Its typically easier to achieve the right layout with the layout xml files. 使用布局xml文件通常更容易实现正确的布局。 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. 如果您还需要在下一行上排列按钮,您还可以使用TableLayout。 Look at the apidemos for code sample. 查看代码示例的apidemos。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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