Вопрос

Hi I am trying to make a layout dynamically and it should be scrollable because I will not know how many text fields and edit text fields I should draw. The picture is shown below.enter image description here

            LinearLayout layout=new LinearLayout(this);
            layout.setOrientation(LinearLayout.VERTICAL);
            layout.setLayoutParams(new LayoutParams(LayoutParams.WRAP_CONTENT,      LayoutParams.WRAP_CONTENT)); 
            setContentView(layout);
Это было полезно?

Решение

Enclose your parent layout (LinearLayout or RelativeLayout) in a ScrollView. Thats all you need to fix this.

ScrollView scroll = new ScrollView(this);
scroll.setLayoutParams(new LayoutParams(LayoutParams.FILL_PARENT,
      LayoutParams.FILL_PARENT));

LinearLayout layout=new LinearLayout(this);
layout.setOrientation(LinearLayout.VERTICAL);
layout.setLayoutParams(new LayoutParams(LayoutParams.WRAP_CONTENT,
      LayoutParams.WRAP_CONTENT)); 

scroll.addView(layout,
      new LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.WRAP_CONTENT));

setContentView(scroll);

Другие советы

ScrollView scrollView = new ScrollView(this);
LinearLayout linear = new LinearLayout(this);


EditText ed1 = new EditText(this);
EditText ed2 = new EditText(this);

linear.add(ed1);  <-- Add all views to Relative layout dynamically 
linear.add(ed2);  <-- Add all views to Relative layout dynamically 

scrollView.addView(linear); <-- Then add only LinearLayoutto ScrollView 

ScrollView can have only one child directly.

setContentView(scrollView);

For java file you can create this xml file like below first and set that in content view

and than

LinearLayout layout=new LinearLayout(this);

instead of this line

RelativeLayout linearMain = (LinearLayout) findViewById(R.id.RelativeLayout02);

and than add your views inside this

linearMain.addView(button);

like above line add your views.

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

      <RelativeLayout
        android:id="@+id/RelativeLayout02"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerInParent="true" >

                    ..............
                    your views

      </RelativeLayout>
  </ScrollView>

There is a layout that does this. Use the ScrollView.

EDIT:

You can do something like this:

LinearLayout layout=new LinearLayout(this);
layout.setOrientation(LinearLayout.VERTICAL);
layout.setLayoutParams(new LayoutParams(LayoutParams.WRAP_CONTENT,      LayoutParams.WRAP_CONTENT)); 
ScrollView scrollLayout = new ScrollView(this);
scrollLayout.addView(layout);
setContentView(scrollLayout);

And just all the controls to layout.

Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top