scrollView上的OnClickListener

Geo*_*aul 16 android

我有一个包含很多元素的scrollView

ScrollView scroller = (ScrollView)findViewById(R.id.scrollView);
Run Code Online (Sandbox Code Playgroud)

我需要将一个onClickListener附加到scrollview,所以我这样做

scroller.setOnClickListener(new OnClickListener() { 
            @Override
            public void onClick(View v) { 
                // This is all you need to do to 3D flip
                AnimationFactory.flipTransition(viewAnimator, FlipDirection.LEFT_RIGHT); 
            }

        });
Run Code Online (Sandbox Code Playgroud)

但是当我触摸时,这并没有被触发.有任何想法吗?

Jul*_*oud 11

最好的解决办法似乎把LinearLayout进入ScrollView,并设置setOnClickListener就可以了.

<ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent">

    <LinearLayout
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"
        android:id="@+id/myLayout"
        android:clickable="true"
        android:orientation="vertical">

       <!-- content here -->
   </LinearLayout>
</ScrollView>
Run Code Online (Sandbox Code Playgroud)

在活动中:

LinearLayout lin = (LinearLayout) fragment.rootView.findViewById(R.id.myLayout);

lin.setOnTouchListener(new setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            // Whatever
        }
});
Run Code Online (Sandbox Code Playgroud)


bak*_*ire 9

这是因为孩子ScrollView正在接受用户的触摸事件而不是ScrollView.必须设置可点击= false属性到每的每一个孩子ScrollViewonClickListener上下工夫ScrollView.

或者替代方案可以是设置onClickListener每个ScrollView的子项并处理它.


bon*_*nyz 8

您需要setOnClickListener 直接在ScrollView的子项上设置.

由于ScrollView只能有一个子项,因此您只需使用此方法:

ScrollView scrollView = //...

View.OnClickListener mOnClickListener = new View.OnClickListener() {
    @Override
    public void onClick(View view) {
        // ...
}

//Set the onClickListener directly on the ScrollView's child
scrollView.getChildAt(0).setOnClickListener(mOnClickListener);
Run Code Online (Sandbox Code Playgroud)