动态添加scrollview中的scrollview和scrollview中的linearlayout

时间:2012-08-03 05:28:20

标签: android scrollview android-linearlayout

如何在布局中动态添加滚动视图?一旦我添加了scrollview,我想在其中添加一个linearlayout,以便我现在可以在该linearlayout中添加控件?

4 个答案:

答案 0 :(得分:7)

我希望它对你有所帮助。

试试此代码......

public class MainActivity extends Activity {

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        RelativeLayout rl=(RelativeLayout)findViewById(R.id.rl);

        ScrollView sv = new ScrollView(this);
        sv.setLayoutParams(new LayoutParams(LayoutParams.MATCH_PARENT,LayoutParams.MATCH_PARENT));
        LinearLayout ll = new LinearLayout(this);
        ll.setLayoutParams(new LayoutParams(LayoutParams.WRAP_CONTENT,LayoutParams.WRAP_CONTENT));
        ll.setOrientation(1);
        sv.addView(ll);

        for(int i = 0; i < 20; i++) 
        {
            Button b = new Button(this);
            b.setText("Button "+i);
            ll.addView(b);
        }

        rl.addView(sv);


        /* If you want to set entire layout as dynamically, then remove below lines in program :
         * setContentView(R.layout.activity_main);
         * RelativeLayout rl=(RelativeLayout)findViewById(R.id.rl);
         * rl.addView(sv);
         * 
         * And Add below line :
         * this.setContentView(sv);

        */

    }

答案 1 :(得分:5)

答案 2 :(得分:-1)

试试这个会起作用:

    TextView tv = new TextView(this);
    tv.setText(msg);       
    tv.setMovementMethod(new ScrollingMovementMethod());
    setContentView(tv);

答案 3 :(得分:-1)

您可以将小部件包装在ScrollView中。这是一个简单的例子:

<ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content">
    <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
        android:orientation="vertical"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent">
        <TextView
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:id="@+id/txt"/>
    </LinearLayout>
</ScrollView>

如果您想在代码中执行此操作:

ScrollView sv = new ScrollView(this);
//Add your widget as a child of the ScrollView.
sv.addView(wView);