[英](Android) How to disable all Buttons/CheckBoxes/Other Widgets inside a ScrollView but not disable the scrolling
我有一個包含ScrollView的Activity。 此ScrollView包含一個TableLayout,其中包含許多小部件。 當用戶單擊一個按鈕時,我想禁用TableLayout內的所有小部件,但不禁用滾動。 用戶需要能夠查看ScrollView內部的內容,但不能與其交互。 我已經在互聯網上搜索了,但是找不到適合我的答案。 如果您有任何解決方案,請在此處發布。 任何幫助將不勝感激。
ScrollView擴展了ViewGroup,因此您可以使用getChildCount()和getChildAt(index)方法來遍歷子級。 因此,它看起來像這樣:
ScrollView scroll = (ScrollView) findViewById(R.id.yourscrollid);
for ( int i = 0; i < scroll.getChildCount(); i++ ){
View view = scroll.getChildAt(i);
view.setEnabled(false); // Or whatever you want to do with the view.
}
您必須在ScrollView
每個視圖上調用setEnabled(false)
。 為了ViewGroup
,您可以將要禁用的所有視圖添加到ViewGroup
,然后在要啟用/禁用子視圖時,只需遍歷ViewGroup
的View。 希望這可以幫助。
我建議您使用框架布局。嘗試以下代碼
xml文件
<?xml version="1.0" encoding="utf-8"?>
<ScrollView 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" >
<FrameLayout
android:layout_width="match_parent"
android:layout_height="wrap_content" >
<TableLayout
android:id="@+id/tablelayout"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="@color/white" >
</TableLayout>
<!-- below frame layout is to disable the whole view -->
<FrameLayout
android:id="@+id/frame"
android:layout_width="match_parent"
android:layout_height="match_parent" />
</FrameLayout>
</ScrollView>
現在,在您的活動中的onCreate()方法內,編寫以下代碼。
FrameLayout fl = (FrameLayout) findViewById(R.id.frame);
fl.setOnTouchListener(new View.OnTouchListener() {
@Override
public boolean onTouch(View v, MotionEvent event) {
return true;
}
});
這將禁止單擊視圖的每個子級。
我最初從Yaw Asare的答案開始,發現它在我的情況下不起作用。 在我的應用程序中遇到此錯誤之前,我已經設置了Player 1和Player 2小部件及其onClick方法。 我必須解決的錯誤是重新實現這些功能並將它們的onClick方法設置為不執行任何操作,然后在我需要再次啟用這些功能時重新調用初始方法。 我實際上並未禁用這些小部件的單擊,而是更改了它們的onClick方法。 非常感謝所有回答此問題的人。 非常感謝您的幫助。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.