[英]How can i use a function from a Activity Class in a non-Activity Class
我的项目中有两个类。第一个是“公共类Schtimetable扩展Activity”,其中需要在B类中调用一个方法:“公共类ClassMode”。该方法是
public int calculateWeeks() {
SharedPreferences preferences = getSharedPreferences("currentWeek",
Context.MODE_PRIVATE);
int csweek = preferences.getInt("CSweek", 1);
int weekofyear = preferences.getInt("currentWeek", 0);
int now_weekofyear = Calendar.getInstance().get(Calendar.WEEK_OF_YEAR);
return (csweek + now_weekofyear - weekofyear);// return current week
}
我发现我不能像这样使用它:
Schtimetable s = new Schtimetable();
int oddOReven = cursor.getInt(cursor.getColumnIndex("oddOReven"));
cursor.close();
if ((s.calculateWeeks() % 2 == oddOReven) || (oddOReven == 2)) {
Log.i(TAG, "has Class is true");
return true;
} else {
Log.i(TAG, "has Class is false");
return false;
}
总之,我想通过方法calculateweeks()返回一个数据,我该如何获取它。 谢谢 !
不要从活动中调用方法。 活动是要开始的,而不是像普通的旧Java对象那样实例化。 将方法放置在其他地方(在其他一些帮助器类中),并以Context作为参数(以便您可以获取SharedPreferences)。 然后,在任何活动中都可以调用该方法。 另外,您可能应该使该方法静态。
这样使用
YourActivtyClass activityclassobject = new YourActivtyClass();
activityclassobject.activityclassmethod();
在您的非活动课程中使用它
这是从另一个活动类中调用的...
我希望您了解调用方法的过程。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.