如何动态地将按钮添加到ScrollView中

时间:2013-05-05 17:31:34

标签: android android-layout android-button android-scrollview

我在向ScrollView动态添加按钮时遇到了困难。下面的代码是添加按钮但没有滚动条。 如果我将按钮直接放在XML中(不是动态的)它正在工作,我可以向下/向上滚动。

我的观点:

<ScrollView android:id="@+id/ScrollView01"
android:layout_width="264dp"
android:layout_height="match_parent"
android:fillViewport="true"
>

    <LinearLayout
        android:id="@+id/buttons"
        android:layout_width="264dp"
        android:layout_height="wrap_content"
        android:orientation="vertical"
        android:scrollbars="vertical"
         >         

     ** HERE THE BUTTONS SHOULD BE ADDED DYNAMICALLY **     

    </LinearLayout>

</ScrollView>

添加按钮的代码:

    // create new button
    final Button newbutton = new Button(this);

    // set background color
    newbutton.setBackgroundColor(Color.GRAY);

    // set width and height
    newbutton.setWidth(50);
    newbutton.setHeight(20);

    // set position
    newbutton.setY(((float)numOfButton*20)+20);
    newbutton.setX(100);

    // set text
    newbutton.setText(Integer.toString(numOfButton));

    // create patameter
    final LinearLayout.LayoutParams p = new LinearLayout.LayoutParams(
            LayoutParams.WRAP_CONTENT,
            LayoutParams.WRAP_CONTENT
            );

    //set listener
    android.view.View.OnClickListener buttonListener = new View.OnClickListener() {

        @Override
        public void onClick(View v) {

            // make all the DrawView invisible
            for(View view : comments){
                view.setVisibility(View.INVISIBLE);
            }

            // set the chosen comment visible
            comments.get(numOfButton).setVisibility(View.VISIBLE);

            boardsHandler.setCurrenBoard(numOfButton);
        }};

        newbutton.setOnClickListener(buttonListener);

        // creating a thread to add button
        buttons.post(new Runnable() { 
            @Override
            public void run() {
                buttons.addView(newbutton, p);
            }
        });

是否属于LinearLayout.LayoutParams p

谢谢!

3 个答案:

答案 0 :(得分:1)

尝试以下代码 先做

LinearLayout myContainer = findViewById(R.id.layoutId);

为视图设置参数时,它们需要与窗口小部件的父视图对应。

LinearLayout.LayoutParams p = new LinearLayout.LayoutParams(
LinearLayout.LayoutParams.WRAP_CONTENT, 
LinearLayout.LayoutParams.FILL_PARENT);

最后在你做的时候添加按钮。

尝试告诉它是否有效

答案 1 :(得分:0)

设置X和Y位置不起作用。 LinearLayout垂直或水平布置它的子项,只考虑它们的宽度/高度。

除此之外 - 您是否尝试在buttons.invalidate()之后致电buttons.addView(...)。这应该刷新布局并显示你的新按钮。

答案 2 :(得分:0)

这是一篇相当古老的文章但我在研究这类问题时发现很快。所以无论如何我都会发布答案,也许这对任何人都有帮助..

我在动态添加按钮的相对布局方面遇到了类似的问题。我发现在添加按钮时手动定义布局大小的解决方法。对于您的情况,添加行

buttons.getLayoutParams().height = numOfButton*20+40;

buttons.addView(newbutton, p);

可能会有所帮助,尽管它可能不是最好的解决方案。 我以为我的错误是使用了RelativeLayout,但是因为你似乎有同样的问题...... 有没有想过使用表格布局?