在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. EditText控件默认总是获取输入法的解决办法
  2. 比achartengine更加强大的Android图表控件。
  3. Android 自定义控件 改变图片颜色来实现类似selector点击更改颜
  4. 《Android开发从零开始》——35.GridView控件学习
  5. Material Design控件使用详解
  6. Android 自定义控件高度设置onMeasure方法
  7. Android控件组合应用二
  8. 通过javascript动态显示界面控件

随机推荐

  1. 我的常用软件大公开!
  2. [每日前端夜话0xBB]
  3. 纯CSS3人物行走动画,超级逼真
  4. 听说你只会用注解,不会自己写注解?
  5. 在 Vue.js 中使用无状态组件[每日前端夜
  6. Node.js 应用最佳实践:日志[每日前端夜话0
  7. 试水JetBrains官方新编程字体,真香!
  8. CSS3超炫酷圆形计时器进度条动画
  9. jQuery 美化界面的下拉框
  10. 昨夜,我梦回武汉 . . .