[英]OnTouchListener inside a method
In my program i'm using this code: 在我的程序中,我使用以下代码:
int value =100;
View.OnTouchListener button1listener = new View.OnTouchListener() {
@Override
public boolean onTouch(View v, MotionEvent event) {
int action = event.getAction();
if (action == MotionEvent.ACTION_DOWN) {
if (value==50) {
System.out.println("button1, value 50");
} else if (value==100) {
System.out.println("button1, value 100");
} else if (value==200) {
System.out.println("button1, value 200");
} else if (action == MotionEvent.ACTION_UP)
System.out.println("No action");
return false;
}
};
button1.setOnTouchListener(button1listener);
It works fine but i want to make it for many buttons, so instead of copying and pasting i would like to have a method for it. 它工作正常,但我想使它用于许多按钮,所以我不想复制和粘贴,而是希望有一种方法。 I tried to do it on my own but my solution isn't correct and i'm not sure how can i make it.
我试图自己做,但是我的解决方案不正确,我不确定该怎么做。 Code below presenting my wrong solution.
下面的代码显示了我的错误解决方案。 So basically i would like to pack this piece of code into a method and then call it with setOnTouchListener and other parameters.
因此,基本上我想将这段代码打包到一个方法中,然后使用setOnTouchListener和其他参数进行调用。
private void setListener(parameter1, String parameter2 ) {
int value =100;
View.OnTouchListener parameter1 = new View.OnTouchListener() {
@Override
public boolean onTouch(View v, MotionEvent event) {
int action = event.getAction();
if (action == MotionEvent.ACTION_DOWN) {
if (value==50) {
System.out.println(parameter2 + "value 50");
} else if (value==100) {
System.out.println(parameter2 + "value 100");
} else if (value==200) {
System.out.println(parameter2 + "value 200");
} else if (action == MotionEvent.ACTION_UP)
System.out.println("No action");
return false;
}
};
}
You can use one interface like this 您可以使用一个这样的界面
public class YourActivity extends AppCompatActivity implements View.OnTouchListener {
@Override
public boolean onTouch(View v, MotionEvent event) {
int action = event.getAction();
if (v.getId() == R.id.button1) { // touched button 1
And when you find the button 当您找到按钮时
findViewById(R.id.button1)
.setOnTouchListener(YourActivity.this);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.