[英]Is there a way to pass a member function into a method by reference? [JAVA]
I'm trying to implement a counter in my app that increases every time the button is clicked. 我正在尝试在我的应用程序中实现一个计数器,该计数器在每次单击按钮时都会增加。 I then want to take the whatever the final value of the counter is and have it displayed in a dialog.
然后,我想获取计数器的最终值是什么,并将其显示在对话框中。
The problem is that when I call the variable, it returns the value that it initially had, not the one modified by the onClick method (This is weird to explain but I commented in my code to show what I mean). 问题在于,当我调用该变量时,它返回的是它最初拥有的值,而不是通过onClick方法修改的值(这很奇怪,但我在代码中注释了一下以表明我的意思)。
final TextView points = (TextView) findViewById(R.id.points);
points.setText("Points = 0");
class ButtonClick implements View.OnClickListener {
int value = 0;
public void onClick(View v) {
value++;
changeLocation(theButton);
points.setText("Points = " + value); // This value increases
}
public int getValue() {
return value;
} // This returns 0.
}
final ButtonClick buttonClicked = new ButtonClick();
theButton.setOnClickListener(buttonClicked);
final int finalValue = buttonClicked.getValue(); // This still equals zero.
Code is executed synchronously line by line: 代码逐行同步执行:
// define and instantiate button listener
1) final ButtonClick buttonClicked = new ButtonClick();
// attach listener to button
2) theButton.setOnClickListener(buttonClicked);
<------ here you still didn't executed onClick :)
// trying get value
3) final int finalValue = buttonClicked.getValue(); // This still equals zero.
When you hit line 3, you are getting value 0 because value is zero. 当您到达第3行时,您将获得值0,因为值是零。
Try clicking (perform click -> do event or whatsoever ) then get value. 尝试单击(执行单击->做事件或执行任何操作),然后获取价值。
To see if it works, you need a second asynchronous method example: 要查看它是否有效,您需要另一个异步方法示例:
new Thread(new Runnable() {
@Override
public void run() {
while(buttonClicked.getValue() ==0) {
// you didn't click
Thread.sleep(10000);
}
};
}).start();
There are couple of issues that I can see, 1) onClick is not the overridden method, so try @Override annotation like this: 我可以看到几个问题:1)onClick不是重写的方法,因此请尝试使用@Override注释,如下所示:
@Override
public void onClick(View v) { ... }
2) When a variable has to be used across, try to declare it in class level with getters and setters also at class level. 2)当必须跨变量使用时,请尝试在类级别使用getter和setter进行声明,该变量也在类级别使用。
Hope these tips will help. 希望这些技巧会有所帮助。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.