在我的Fragment类中,我用XML Layout来填充我的片段。布局是一个简单的LinearLayout,其中带有ImageView(车轮的)。我想获取发生在ImageView上的触摸事件,这是代码:

 public class WheelFragment extends Fragment {


   @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {

         // Inflate the layout for this fragment (Get the view from XML)
        View view = inflater.inflate(R.layout.wheel_layout, container, false);

        // Get the imageview of the wheel inside the view
        ImageView wheelView = (ImageView) view.findViewById(R.id.wheel);


        // Set onTouchListener
        wheelView.setOnTouchListener(new OnTouchListener() {
        public boolean onTouch(View v, MotionEvent event) {


            if (event.getAction() == MotionEvent.ACTION_DOWN) {
                    Log.d("down", "ACTION_DOWN");
                }

            if (event.getAction() == MotionEvent.ACTION_UP) {
                        Log.d("up", "ACTION_UP");
                }
            }

            return true;
        }
        });



        // Return the view
        return view;
    }
}


我没有遇到ACTION_DOWN事件,但是我没有获得ACTION_UP事件。

我试图添加一个ACTION_CANCEL事件,该事件没有帮助(我在论坛上看到它可能可以解决问题)。

我也尝试将值true / false都返回。

有什么简单的方法可以使ACTION_UP事件起作用?
谢谢。

最佳答案

好吧,我终于找到了解决方案。

首先,我的代码真的很乱,因为我将OnTouch放在OnCreateView中,然后我需要在类中添加“ impements OnTouchListener”。

这是有效的代码:

    public class WheelFragment extends Fragment implements OnTouchListener {


        @Override
        public View onCreateView(LayoutInflater inflater, ViewGroup container,
                                 Bundle savedInstanceState) {

             // Inflate the layout for this fragment (Get the view from XML)
            View view = inflater.inflate(R.layout.wheel_layout, container, false);

            // Get the imageview of the wheel inside the view
            ImageView wheelView = (ImageView) view.findViewById(R.id.wheel);


            // Set onTouchListener
            wheelView.setOnTouchListener(this);
            return view;
        }



    public boolean onTouch(View v, MotionEvent event) {
        if (event.getAction() == MotionEvent.ACTION_DOWN) {
            Log.d("down", "ACTION_DOWN");
        }
        if (event.getAction() == MotionEvent.ACTION_UP) {
            Log.d("up", "ACTION_UP");
        }
        return true;
    }



}


(实际上,如果我们在OnTouch中返回false则不起作用,但我不需要任何ACTION_CANCEL即可使其工作)

关于android - ACTION_UP出现问题,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/10777555/

10-12 00:19
查看更多