如何处理在Fragment中点击ScrollView?

时间:2017-10-22 13:18:28

标签: java android android-fragments

如何处理片段中的ScrollView?

<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>

在Fragment中我尝试:

@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();
        }
    });
}

但点击后没有任何反应。

处理片段点击的任何其他想法?这不一定是ScrollView。我也试过FragmentLayout,但它返回了很多错误。

2 个答案:

答案 0 :(得分:0)

在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();
    }
});

答案 1 :(得分:0)

解释了ScrollView的onClickListener被忽略的原因here

你可以像这样添加一个onTouchListener。

    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;
        }
    });