代码之家  ›  专栏  ›  技术社区  ›  fredley

线性布局从右向左填充

  •  5
  • fredley  · 技术社区  · 14 年前

    我想创建一个输入框,在右边有一个提交按钮。它们之间应该跨越屏幕的宽度。目前我有:

    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 回复  |  直到 14 年前
        1
  •  4
  •   Konstantin Burov    14 年前

    我想说,最好使用相对布局并将输入放在按钮的左侧。但是,如果您真的需要线性布局,您可以只使用权重参数:

        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);
    
        2
  •  3
  •   Asahi    14 年前

    尝试添加 EditText 首先将其宽度设置为 fill parent 它的重量为1,然后按钮(宽度= wrap content )

        3
  •  0
  •   Cheryl Simon    14 年前

    项目按添加顺序以线性布局堆叠。切换两个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>
    
        4
  •  0
  •   Jack    14 年前

    如果还需要在下一行排列按钮,也可以使用TableLayout。查看apidemos中的代码示例。