问题
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.
LinearLayout layout=new LinearLayout(this);
layout.setOrientation(LinearLayout.VERTICAL);
layout.setLayoutParams(new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT));
setContentView(layout);
回答1:
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);
回答2:
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);
回答3:
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>
回答4:
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
.
来源:https://stackoverflow.com/questions/11469716/how-to-create-a-scrollable-layout