ScrollView滚动视图:
用于给普通组件添加一个垂直滚动条,最多包含一个组件,ScrollView与Swing中的JScrollPanel类似
甚至不能称为容器,只是为其他容器添加滚动条
水平方向的滚动条要使用:HorizontalScrollView
实例:
实现ScrollView垂直滚动和HorizontalScrollView水平滚动的视图
只需要在main.xml文件中创建
代码:
main.xml
- <span style="font-family:Comic Sans MS;"><ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
- android:layout_width="match_parent"
- android:layout_height="match_parent">
- <HorizontalScrollView
- android:layout_width="match_parent"
- android:layout_height="wrap_content">
- <LinearLayout
- android:id="@+id/LinearLayout1"
- android:layout_width="wrap_content"
- android:layout_height="wrap_content"
- android:orientation="vertical" >
- <TextView
- android:layout_width="wrap_content"
- android:layout_height="wrap_content"
- android:textSize="60sp"
- android:text="@string/hello_world" />
- <TextView
- android:layout_width="wrap_content"
- android:layout_height="wrap_content"
- android:textSize="60sp"
- android:text="@string/hello_world" />
- <TextView
- android:layout_width="wrap_content"
- android:layout_height="wrap_content"
- android:textSize="60sp"
- android:text="@string/hello_world" />
- <TextView
- android:layout_width="wrap_content"
- android:layout_height="wrap_content"
- android:textSize="60sp"
- android:text="@string/hello_world" />
- <TextView
- android:layout_width="wrap_content"
- android:layout_height="wrap_content"
- android:textSize="60sp"
- android:text="@string/hello_world" />
- <TextView
- android:layout_width="wrap_content"
- android:layout_height="wrap_content"
- android:textSize="60sp"
- android:text="@string/hello_world" />
- <TextView
- android:layout_width="wrap_content"
- android:layout_height="wrap_content"
- android:textSize="60sp"
- android:text="@string/hello_world" />
- <TextView
- android:layout_width="wrap_content"
- android:layout_height="wrap_content"
- android:textSize="60sp"
- android:text="@string/hello_world" />
- </LinearLayout>
- </HorizontalScrollView>
- </ScrollView></span>
就是用ScrollView和HorizontalScrollView包裹住我们的容器LinearLayout,然后就可以了
运行截图:
二.当然我们也可以在MainActivity中设置一些属性
实例:在java文件中设置scrollView的初始位置
代码:
- <span style="font-family:Comic Sans MS;">private ScrollView scroll;
- private HorizontalScrollView hscroll;
- private LinearLayout line;
- @Override
- protected void onCreate(Bundle savedInstanceState) {
- super.onCreate(savedInstanceState);
- setContentView(R.layout.activity_main);
- scroll = (ScrollView) findViewById(R.id.scroll);
- hscroll = (HorizontalScrollView) findViewById(R.id.hscroll);
- line = (LinearLayout) findViewById(R.id.LinearLayout1);
- scroll.scrollTo(0,line.getBottom());
- hscroll.scrollTo(line.getWidth(), 0);
- }</span>
这里的话我们利用.scrollTo方法去设置滚动条的起始位置,参数分别为x,y轴坐标
运行结果如上图,这里略过...