0

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.

Dima Kozhevin
  • 3,602
  • 9
  • 39
  • 52
  • 1
    did you make debugging? does onclick function run properly? Does the toast show runs properly but does not occur on your screen? Where does the error occurs exactly? – koksalb Oct 22 '17 at 13:25

2 Answers2

0

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();
    }
});
Sush
  • 3,864
  • 2
  • 17
  • 35
0

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;
        }
    });
Venkata Narayana
  • 1,657
  • 12
  • 25