How to use Android Scrollview via Java code?

Asked

Viewed 1,571 times

0

In xml it’s easy to use, but I’m making a dynamic form and it’s not working. I’m doing something like this:

ScrollView scroll = new ScrollView(this);

From there inside the onCreate() I use it:

scroll.addView(activity_main);
setContentView(scroll);

But it is giving error. set the Layoutparams in it also does not function.

  • 1

    What’s the mistake ?

2 answers

1

To use your layout in . xml, you need to inflate it into a View:

LayoutInflater inflater = (LayoutInflater) getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE); 
View viewExemplo = inflater.inflate(R.layout.seu_layout, null);
scrollView.addView(viewExemplo);

0

You can create an xml and call it scrollview.xml

<?xml version="1.0" encoding="utf-8"?>
<ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content">

    <LinearLayout
        android:id="@+id/linearContent"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="vertical">

    </LinearLayout>
</ScrollView>

Via code, you get the container that will receive the views.

View scrollView = LayoutInflater.from([contexto aqui]).inflate(R.layout.scrollview, null);

LinearLayout mLinearContainer = (LinearLayout)scrollView .findViewById(R.id.linearContent);

 // nesse mLinearContainer  você adiciona as views
  • I hadn’t noticed that you would use this layout in Activity, so just do setContentView(R.layout.scrollview) and find it directly, without needing Layoutinflater.from([context here]). inflate(R.layout.scrollview, null); Remember that Scrollview must have only one direct child and must be Viewgroup, i.e., Relativelayout, Linearlayout, etc.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.