你好,我有一个记忆游戏课程: 一个是具有该方法的NV1,例如:
public class Nv1 extends Activity{
protected int cardsUp;
protected int currentIndex = -1;
protected int lastIndex = -1;
protected int cardEquals = 0;
protected int lifes = 3;
protected TextView lifes_txt;
protected Handler handler;
protected int [] imgIds = {
R.id.img_1,
R.id.img_2,
R.id.img_3,
R.id.img_4,
};
另一个实现OnClickListener的类NVListener。
public class CardsListener implements OnClickListener{
@Override
public void onClick(View v) {
我需要从我的Activity调用方法到CardsListener。我怎么能这样做?
答案 0 :(得分:0)
方法A:使侦听器抽象化,在Activity中实现onClick的抽象方法 (推荐,监听器可以轻松重用,更容易调试)
示例:
在SampleActivity.java中
public class SampleActivity extends Activity {
Button b;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//Your code here.....
// findViewById()..... etc.
b.setOnClickListener(new SomeListener(){
@Override
public void onClick(View v) {
someMethod();
}
});
}
public void someMethod(){
Log.d("Log Tag","Some Message");
}
}
在SomeListener.Java中
//make it abstract
public abstract class SomeListener implements OnClickListener{
//put your own method,variables inside
//do not override onClick()
}
方法B:使用Activity作为输入参数创建构造函数。保存活动实例并自由调用其方法(少推荐:不灵活,不是逻辑IMO)
在SomeListener.Java中
public class SomeListener implements OnClickListener {
private SampleActivity mAct;
public SomeListener(SampleActivity act){
mAct = act;
}
@Override
public void onClick(View v) {
mAct.someMethod();
}
}