(Android) 如何在 ScrollView 中禁用所有 Buttons/CheckBoxes/Other 小部件但不禁用滚动

(Android) How to disable all Buttons/CheckBoxes/Other Widgets inside a ScrollView but not disable the scrolling

我有一个包含 ScrollView 的 Activity。这个 ScrollView 包含一个 TableLayout,里面有很多 Widgets。当用户单击一个按钮时,我想禁用 TableLayout 中的所有小部件,但不禁用滚动。用户需要能够查看 ScrollView 内部的内容,但不能与之交互。我在互联网上搜索过,但未能找到适合我的答案。如果您有任何解决方案,请在此处post。非常感谢任何帮助。

ScrollView 扩展了 ViewGroup,因此您可以使用 getChildCount() 和 getChildAt(index) 方法遍历您的 children。 所以,它看起来像这样:

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,然后当您想要 enable/disable 时,子视图只需遍历 ViewGroup 中的视图。希望这可以帮助。

我建议您使用 it.Try 以下代码的框架布局

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>

现在在你的 activity 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 的回答开始的,但发现它在我的情况下不起作用。在 运行 进入我的应用程序中的这个错误之前,我已经设置了播放器 1 和播放器 2 小部件及其 onClick 方法。为了修复我的错误,我必须做的是重新实现这些功能并将它们的 onClick 方法设置为不执行任何操作,然后在我需要再次启用这些方法时调用初始方法。我实际上并没有禁用这些小部件的点击,而是更改了它们的 onClick 方法。非常感谢所有回答这个问题的人。非常感谢您的帮助。