SleepNot
SleepNot

Reputation: 3038

Dynamically add scrollview in layout and linearlayout in scrollview

How do I dynamically add a scrollview in my layout? and once I get that scrollview added I want to add a linearlayout inside it so I can now add controls in that linearlayout?

Upvotes: 5

Views: 33452

Answers (4)

Yash
Yash

Reputation: 1751

You can wrap your widget inside a ScrollView. Here's a simple example:

<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>

If you want to do it in code:

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

Upvotes: -1

nam_ph
nam_ph

Reputation: 233

try this it will work :

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

Upvotes: -1

Balaji
Balaji

Reputation: 2026

I hope it will helpful to you.

Try this Code...

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);

        */

    }

Upvotes: 8

Related Questions