如何为Android片段中的多个按钮定义setOnTouchListener [英] How to define setOnTouchListener for multiple buttons in Android fragment

查看:89
本文介绍了如何为Android片段中的多个按钮定义setOnTouchListener的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个带有多个按钮的片段.我为每个按钮创建了一个 setOnTouchListener ,例如下面的代码.

I have a fragment with multiple buttons. For each button I created a setOnTouchListener, such as the code below.

Button btnOne = (Button) view.findViewById(R.id.button_one);
Button btnTwo = (Button) view.findViewById(R.id.button_two);

btnOne.setOnTouchListener(new View.OnTouchListener() {
    @Override
    public boolean onTouch(View v, MotionEvent event) {
        myMethod(btnOne);
        return false;
    }
});

btnTwo.setOnTouchListener(new View.OnTouchListener() {
    @Override
    public boolean onTouch(View v, MotionEvent event) {
        myMethod(btnTwo);
        return false;
    }
});

如何创建通用方法 setOnTouchListener 以在所有按钮中使用?我想要这样的东西:

How could I create a generic method setOnTouchListener to use in all buttons? I'd like to have something like this:

btnOne.method();
btnTwo.method();
btnThree.method();
...

推荐答案

您正在使用内部匿名类对象,该对象实现了 View.OnTouchListener 接口.

You are using inner anonymous class objects which implements the interface View.OnTouchListener.

如果我是你,最好在 Fragment (或其他独立的外部类)中实现该接口:

If I were you, better implement the interface in the Fragment (or other independent outer class):

public class MyFragment extends Fragment implements View.OnTouchListener {

    (...)

    @Override
    public boolean onTouch(View v, MotionEvent event) {
        return myMethod(v);
    }

    (...)

}

并使用参数 View v 定义 myMethod .您可以通过每个 View 对象的 id (在Emanuel Moecklin的答案中已经提到过)来区分按钮.

And define myMethod with argument View v. You can distinguish buttons with each View object's id (that has already been mentioned in Emanuel Moecklin's answer).

public class MyFragment extends Fragment implements View.OnTouchListener {

    (...)

    private boolean myMethod(View v) {
        switch (v.getId()) {
        case R.id.button_one:
            (...)
            return true;
        case R.id.button_two:
            (...)
            return true;
        case R.id.button_three:
            (...)
            return true;

        (...)

        default:
            return false;
        }
    }

    (...)

}

最后,您可以非常巧妙地为多个按钮设置相同的 OnTouchListener 对象.

Finally, you can set the same OnTouchListener object for multiple buttons quite smartly.

Button btnOne = (Button) view.findViewById(R.id.button_one);
Button btnTwo = (Button) view.findViewById(R.id.button_two);

btnOne.setOnTouchListener(this);
btnTwo.setOnTouchListener(this);

这篇关于如何为Android片段中的多个按钮定义setOnTouchListener的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆