我有两个java文件。主要活动包含以下内容:
String randomEvent;
public void randomTrigger(){
int min = 1;
int max = 100;
Random randomTrigger = new Random();
int randomNumber = randomTrigger.nextInt(max - min) + min;
RandomEvent obj = new RandomEvent();
if (randomNumber == 7) {
// What do I put here to call the method randomEvent(); in RandomEvent.java ?
}
}
saveSettings();{
SharedPreferences settings = getSharedPreferences("com.******.******", MODE_PRIVATE);
settings.edit().putString("randomEvent", randomEvent).commit();
}
第二个名为“RandomEvent.java的活动是MainActivity的子类:
package com.******.******;
import android.content.SharedPreferences;
public class RandomEvent extends MainActivity {
public void randomEvent() {
MainActivity obj = new MainActivity();
obj.randomEvent = "You've received a pay raise!";
payRate = payRate * 1.1f;
saveSettings();
}
}
我的问题是,如何正确执行randomEvent();位于超类MainActivity中的RandomEvent.java类文件中的方法?
答案 0 :(得分:0)
通过这样做可以实现: -
public class MainActivity{
public void randomEvent() {}
}
public class RandomEvent extends MainActivity{
@Override
public void randomEvent() {
//You stuff
}
}
在此方法中,您可以从MainActivity中调用 randomEvent 。 但最好这样做: -
public interface Events{
public void randomEvent();
}
public abstract class MainActivity implements Events{
}
public class RandomEvent extends MainActivity{
@Override
public void randomEvent() {
//You stuff
}
}
最好是以这种方式保持代码清洁,或者你可以做的其他事情是: -
public interface Events{
public void randomEvent();
}
public class MainActivity{
public Events getEvents(){
return null;
}
public void randomTrigger(){
Events events = getEvents();
if(null != events){
events.randomEvent();
}
}
}
}
public class RandomEvent extends MainActivity implements Events{
@Override
public void randomEvent() {
//You stuff
}
@Override
public Events getEvents(){
return this;
}
}
最好的是最后一个。