如何创建可滚动的布局

时间:2012-07-13 11:36:06

标签: android layout scrollable

您好我正在尝试动态制作布局,它应该是可滚动的,因为我不知道应该绘制多少文本字段和编辑文本字段。图片如下所示。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);

4 个答案:

答案 0 :(得分: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 

ScrollView只能直接拥有一个孩子。

setContentView(scrollView);

答案 1 :(得分: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);

答案 2 :(得分: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的所有控件。

答案 3 :(得分: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>
相关问题