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