2012-07-13 82 views
1

嗨我想要动态布局,它应该是可滚动的,因为我不知道我应该绘制多少个文本字段和编辑文本字段。图片如下所示。 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); 
+0

在XML中进行滚动查看。然后将运行时其他视图添加到它。 – 2012-07-13 11:38:11

+0

@ answer88发布您的xml文件。 – 2012-07-13 11:40:30

+0

我想使它在Java文件中。 – answer88 2012-07-13 11:40:36

回答

2

将您的父布局(LinearLayout或RelativeLayout)包含在ScrollView中。这就是你需要解决这个问题。

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

看到我更新的答案 – waqaslam 2012-07-13 11:47:32

1

有一个这样的布局。使用ScrollView

编辑:

你可以做这样的事情:

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

而就在所有的控件layout

+0

我该如何在java文件中实现它。我正在java文件中动态创建布局。 – answer88 2012-07-13 11:41:15

1

对于Java文件,你可以像下面先创建该XML文件,并设置在内容视图

,比

LinearLayout layout=new LinearLayout(this); 

,而不是这一行

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

和比在此添加您的看法

linearMain.addView(button); 

像上面一行添加您的意见。

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

滚动型可以直接只生一个孩子。

setContentView(scrollView);