设置视图宽度与其他视图相同

时间:2013-01-10 14:08:43

标签: android layout

我有一个线性布局,有两个相等重量的按钮。因此它们占据整个屏幕(宽度方面)。

在第一个下方的另一个线性布局中,我只有一个按钮,其宽度我希望与前两个按钮中的任何一个相同。

除了使用gridview或tableview等之外,还有一种简单的方法吗,

我试过了:

Button one = (Button) findViewById(R.id.one);
Button two = (Button) findViewById(R.id.two);
Button three = (Button) findViewById(R.id.three);

three.setLayoutParams(new LinearLayout.LayoutParams(
        one.getLayoutParams()));

布局:

<LinearLayout
            xmlns:android="http://schemas.android.com/apk/res/android"
            xmlns:tools="http://schemas.android.com/tools"
            android:id="@+id/first"
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:orientation="horizontal" >

        <Button
            android:id="@+id/one"
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_weight="1" />

        <Button
            android:id="@+id/two"
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_weight="1" />
    </LinearLayout>

    <LinearLayout
        xmlns:android="http://schemas.android.com/apk/res/android"
        xmlns:tools="http://schemas.android.com/tools"
        android:id="@+id/second"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_below="@id/first"
        android:orientation="horizontal" >

        <Button
            android:id="@+id/three"
            android:layout_width="150dp"
            android:layout_height="wrap_content" />
    </LinearLayout>

但是第3个按钮现在是不可见的。

谢谢

3 个答案:

答案 0 :(得分:1)

尝试第二行

<LinearLayout
    android:id="@+id/second"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:layout_below="@id/first1"
    android:weightSum="2"
    android:orientation="horizontal" >

    <Button
        android:layout_weight="1"
        android:id="@+id/three"
        android:layout_width="0dp"
        android:layout_height="wrap_content" />
</LinearLayout>

答案 1 :(得分:0)

您可以使用get和set width方法设置java代码中第3个按钮的宽度。

获取其他按钮的宽度,并将其设置为第3个按钮的宽度。

其次,您的第3个按钮是不可见的,因为您的2个LinearLayouts周围没有根布局。

你应该在它周围添加第三个“root”LinearLayout,android:orientation =“vertical”

答案 2 :(得分:0)

第三个按钮不可见的原因是因为在构建(和设置)新的LinearLayout.LayoutParams时通过

three.setLayoutParams(new LinearLayout.LayoutParams(one.getLayoutParams()));

重量不会转移到新的LinearLayout.LayoutParams。

您可以使用以下代码来解决问题:

LinearLayout.LayoutParams newlayout = new LinearLayout.LayoutParams(one.getLayoutParams());
    newlayout.weight = 1;
    three.setLayoutParams(newlayout);

或者您可以使用另一个构造函数( LinearLayout.LayoutParams (int width, int height, float weight)),它明确地获取权重:

LayoutParams param = new LinearLayout.LayoutParams(one.getLayoutParams().width, one.getLayoutParams().height,((LinearLayout.LayoutParams) one.getLayoutParams()).weight);
three.setLayoutParams(param);

现在也应该看到三个。

相关问题