2012-07-13 84 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);