【问题标题】:Resize parent LinearLayout when adding Buttons Programatically以编程方式添加按钮时调整父 LinearLayout 的大小
【发布时间】:2012-02-06 20:54:26
【问题描述】:

所以我想做的是向 LinearLayout 程序添加按钮,这很好用。我希望它们以水平顺序显示为一行按钮,因此我将 LinearLayout 设置如下:

<LinearLayout
android:id="@+id/button_frame"
android:orientation="horizontal"
android:layout_width="fill_parent"
android:layout_height="wrap_content">

</LinearLayout>

然后我以编程方式添加按钮:

for (String text: textlist) {

        Button cbut = new Button(context);
        cbut.setText(text);
        cbut.setLayoutParams(new ViewGroup.LayoutParams(
                ViewGroup.LayoutParams.WRAP_CONTENT,
                ViewGroup.LayoutParams.WRAP_CONTENT));
        cbut.setOnClickListener(new Button.OnClickListener() {

            @Override
            public void onClick(View arg0) {
                Log.d(LOGTAGNAME, "TEST: " + buttonText);
            }
        });

        button_frame.addView(cbut);
        button_frame.invalidate();
    }

这一直有效,直到按钮扩展屏幕宽度。所以我想要发生的是,如果按钮扩展屏幕宽度,则会有一个水平 scollbar。作为替代方案,LinearLayout 内的按钮可能会有“换行符”。

我尝试了不同的设置,包括列表视图周围的滚动视图,但我从未见过滚动条。

所以也许我的问题是 LinearLayout 没有正确调整大小?每次添加视图后,我该怎么做才能使 LinearLayout 重新计算宽度? invalidate() 完全没有效果。

感谢您的帮助。

【问题讨论】:

    标签: android resize android-linearlayout


    【解决方案1】:

    尝试将线性布局放在水平滚动视图中。一旦按钮超过屏幕宽度,它应该提供滚动条。

    【讨论】:

    • 您好,非常感谢。这就是我需要做的。使用水平滚动视图而不仅仅是滚动视图。现在可以了!
    【解决方案2】:

    您尝试简单的滚动视图或http://developer.android.com/reference/android/widget/HorizontalScrollView.html?如果您不尝试 Horizo​​ntalScrollView,我认为这一定会有所帮助。

    【讨论】:

      【解决方案3】:

      尝试HorizontalScrollView 并向其添加按钮。这将在需要时自动滚动。如需更多帮助,请分享完整的布局代码

      【讨论】:

        【解决方案4】:

        LinearLayout 仅提供视图的“线性”定位;)我的意思是您可以这样做:

        [btn1][btn2][btn3][btn4]
        

        或者像这样:

        [btn1]
        [btn2]
        [btn3]
        [btn4]
        

        两个变体之间的区别在于android:orientation 参数。对于更复杂的视图,您应该使用TableLayoutRelativeLayout

        如果你想做线性布局creta这个结构的可滚动变体:

        <HorizontalScrollView
             android:layout_width="fill_parent"
             android:layout_height="wrap_content"
             ...any other params...>
            <LinearLayout
                 android:layout_width="fill_parent"
                 android:layout_height="wrap_content"
                 android:orientation="horisontal"
                 ...any other params.../>
        </HorizontalScrollView>
        

        并像现在一样将按钮添加到线性布局。

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2017-07-20
          • 2018-07-13
          • 1970-01-01
          相关资源
          最近更新 更多