我的 MainActivity 中有 900 多行,因为我不知道如何让其他类工作。
它可以工作,但很难阅读并且更新起来很乏味。
我将举例说明我想要分离到另一个类的内容。
我想从主要 Activity 中调用它。
主要 Activity :
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.apm:
apm();
return true;
}
public void apm() {
AlertDialog levelDialog;
final CharSequence[] items = {" Reboot ", " Reboot Recovery ", " Hot Reboot "};
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle("What do you want to do?");
builder.setCancelable(true);
builder.setSingleChoiceItems(items, -1, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int item) {
switch (item) {
case 0:
rooted();
reboot();
break;
case 1:
rooted();
recovery();
break;
case 2:
rooted();
softreboot();
break;
//case 3:
//shutdown();
//break;
}
}
});
levelDialog = builder.create();
levelDialog.show();
}
最佳答案
在新文件 Util.java 中创建一个名为 Util(例如)的新类。
在这个类中放:
public static void apm(MainActivity activity){
//Put the code from your old apm method here.
//Whenever you need to call a method that is part of MainActivity
//just prepend activity. in front of the method call.
}
然后在MainActivity中,调用Util.apm(this);
。
编辑:
这里有更多细节。将以下内容放入 Util.java 并在您的 MainActivity 中调用 Util.apm(this);
。
public static void apm(MainActivity activity) {
AlertDialog levelDialog;
final CharSequence[] items = {" Reboot ", " Reboot Recovery ", " Hot Reboot "};
AlertDialog.Builder builder = new AlertDialog.Builder(activity);
builder.setTitle("What do you want to do?");
builder.setCancelable(true);
builder.setSingleChoiceItems(items, -1, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int item) {
switch (item) {
case 0:
activity.rooted();
activity.reboot();
break;
case 1:
activity.rooted();
activity.recovery();
break;
case 2:
activity.rooted();
activity.softreboot();
break;
//case 3:
//activity.shutdown();
//break;
}
}
});
levelDialog = builder.create();
levelDialog.show();
}
关于java - 如何模块化长代码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18222058/