在Android中,ListView通常用来实现纵向滚动的列表,而HorizontalScrollView则可以实现横向滚动的列表项。

引入HorizontalScrollView控件很简单,例如在一个LinearLayout中:

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"    xmlns:tools="http://schemas.android.com/tools"    android:layout_width="match_parent"    android:layout_height="match_parent"    android:orientation="vertical" >    <HorizontalScrollView         android:layout_width="match_parent"        android:layout_height="wrap_content">     HorizontalScrollView>LinearLayout>

这时我们没有添加任何子控件,因此IDE提示我们“This HorizontalScrollView view is useless (no children, no background, no id, no style)

作为示例,我们尝试在这个HorizontalScrollView中添加若干个按钮:

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"    xmlns:tools="http://schemas.android.com/tools"    android:layout_width="match_parent"    android:layout_height="match_parent"    android:orientation="vertical"    tools:context="com.example.viewholdertest.MainActivity" >    <HorizontalScrollView         android:layout_width="match_parent"        android:layout_height="wrap_content">        <Button             android:layout_width="wrap_content"            android:layout_height="wrap_content"            android:text="Hello"/>        ......(余下的省略)    HorizontalScrollView>LinearLayout>

这时IDE会提示我们:“A scroll view can have only one child”。
原来,在HorizontalScrollView中,只可存在一个直接的子View。因此正确的用法是使用一个如LinearLayout这样的控件,将多个子View放入其中,改好的布局文件是这样的:

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"    xmlns:tools="http://schemas.android.com/tools"    android:layout_width="match_parent"    android:layout_height="match_parent"    android:orientation="vertical"    tools:context="com.example.viewholdertest.MainActivity" >    <HorizontalScrollView        android:layout_width="match_parent"        android:layout_height="wrap_content" >        <LinearLayout            android:layout_width="wrap_content"            android:layout_height="wrap_content"            android:orientation="horizontal" >            <Button                android:layout_width="wrap_content"                android:layout_height="wrap_content"                android:text="Hello" />            ......(余下的省略)        LinearLayout>    HorizontalScrollView>LinearLayout>

注意HorizontalScrollView中LinearLayout的witdh属性应为”wrap_content”。


现在运行APP,便可以通过横向滑动,将多余的按钮显示出来了。

更多相关文章

  1. 三、安卓UI学习(1)
  2. android用户界面之按钮(Button)教程实例汇
  3. 在Fragment中设置控件点击方法,执行失败。
  4. TabHost与RadioGroup结合完成的菜单【带效果图】5个Activity
  5. Android常用控件
  6. android用户界面-组件Widget-画廊视图Gallery
  7. 总目录
  8. android 单元测试
  9. android 布局式跑马灯,非TextView

随机推荐

  1. android系统
  2. iPhone和Android,谁将成为赢家?
  3. Android(安卓)HAL 开发 (1)
  4. sdcardFS(android sdcard存储方案---基于w
  5. Android中如何修改编译的资源ID值(默认值
  6. Android与设计模式浅谈
  7. 最新!!Android(安卓)状态栏详细开发,5分钟精
  8. Android(安卓)Opengl开发一
  9. 打造android万能上拉下拉刷新框架——XRe
  10. Android测试方法总结汇总