Home » Android » How to handle click on ScrollView in Fragment?

How to handle click on ScrollView in Fragment?

Posted by: admin November 1, 2017 Leave a comment

Questions:

How to handle click on ScrollView in Fragment?

<FrameLayout 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"
    tools:context=".ExampleFragment">

        <ScrollView
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:id="@+id/myScroll">
        </ScrollView>

</FrameLayout>

And in Fragment I’m trying:

@Override
public void onStart() {
    super.onStart();

    ScrollView refresh = (ScrollView) getActivity().findViewById(R.id.myScroll);
    refresh.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            Toast toast = Toast.makeText(getActivity().getApplicationContext(), "TEST", Toast.LENGTH_LONG);
            toast.show();
        }
    });
}

But after clicking nothing happens.

Any other idea to handle a click on a fragment? This does not have to be a ScrollView. I tried also for FragmentLayout but it returns a lot of bugs.

Answers:

The reason for the onClickListener of ScrollView being ignored is explained here.

You could add an onTouchListener instead like this.

    refresh.setOnTouchListener(new View.OnTouchListener() {
        /**
         * Called when a touch event is dispatched to a view. This allows listeners to
         * get a chance to respond before the target view.
         *
         * @param v     The view the touch event has been dispatched to.
         * @param event The MotionEvent object containing full information about
         *              the event.
         * @return True if the listener has consumed the event, false otherwise.
         */
        @Override
        public boolean onTouch(View v, MotionEvent event) {
           Toast toast = Toast.makeText(getActivity().getApplicationContext(), "TEST", Toast.LENGTH_LONG);
           toast.show();             
           return false;
        }
    });

Questions:
Answers:

use this code in onCreateView

 ScrollView refresh = (ScrollView) getActivity().findViewById(R.id.myScroll);
refresh.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View v) {
        Toast toast = Toast.makeText(getActivity().getApplicationContext(), "TEST", Toast.LENGTH_LONG);
        toast.show();
    }
});