Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲

解決Android ScrollView只能容納一個直接子控件的問題

編輯:關於 Android 程式設計

本文將分享Android ScrollView只能添加一個子控件這一常見問題的解決方法,供有需要的朋友參考。

先來看下面這段代碼:

 <?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="https://schemas.android.com/apk/res/android" android:layout_width="fill_parent" android:layout_height="fill_parent" android:orientation="vertical" > <ScrollView android:layout_width="fill_parent" android:layout_height="fill_parent" > <Button android:layout_width="fill_parent" android:layout_height="wrap_content" /> <Button android:layout_width="fill_parent" android:layout_height="wrap_content" /> <Button android:layout_width="fill_parent" android:layout_height="wrap_content" /> </ScrollView> </LinearLayout> 

這裡在一個ScrollView裡直接放了三個Button。乍看之下似乎沒什麼問題,但一運行就會拋出異常:

異常信息很明確:ScrollView can host only one direct child(ScrollView只能容納一個直接子控件)。

既然只能有一個直接子控件,那我們就在這些子控件外面再套一層LinearLayout,讓它們成為間接子控件即可:

 <?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="https://schemas.android.com/apk/res/android" android:layout_width="fill_parent" android:layout_height="fill_parent" android:orientation="vertical" > <ScrollView android:layout_width="fill_parent" android:layout_height="fill_parent" > <LinearLayout android:layout_width="fill_parent" android:layout_height="fill_parent" android:orientation="vertical" > <Button android:layout_width="fill_parent" android:layout_height="wrap_content" /> <Button android:layout_width="fill_parent" android:layout_height="wrap_content" /> <Button android:layout_width="fill_parent" android:layout_height="wrap_content" /> </LinearLayout> </ScrollView> </LinearLayout> 

更多Android相關內容感興趣的讀者,可查看本站專題:《Android開發入門與進階教程》、《Android多媒體操作技巧匯總(音頻,視頻,錄音等)》、《Android基本組件用法總結》、《Android視圖View技巧總結》、《Android布局layout技巧總結》及《Android控件用法總結》。

希望本文所述對大家的Android程序設計有所幫助。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © Android教程網 All Rights Reserved