假设我有一个名为 MainActivity.java
的 Activity 类。但是这个 Activity 有大约 3000 行代码。
我想将此文件的代码部分分离到名为 NecessaryThings.java
的外部 java 文件(类)中。但是,如果我在模拟器上运行我的项目,它会在此操作后自行停止。
有没有办法将此 Activity 的某些行分开?
为了更好,我写了一个小例子..
还有你怎么看;
使用这种方法对性能有利还是有害?
这是我的 MainActivity.java
public class MainActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//I want to call these lines from NecessaryThings.java
TextView genderResult = (TextView) findViewById(R.id.genderText);
genderResult.setText("Cinsiyet:");
TextView calorieResult = (TextView) findViewById(R.id.remainCalorie);
String getGenderSTR = getIntent().getStringExtra("GENDER");
genderResult.setText(getGenderSTR);
String calorieResultSTR = getIntent().getStringExtra("CALORIECHOOSED");
calorieResult.setText(calorieResultSTR);
/*
.....
.....
*/
}
Aftet 我拿了上面的代码,然后我想把它存储在 NecessaryThings.java
像这样..
//All necessary imports here. There is no problem about those.
public class NecessaryThings extends Activity {
public void myPersonalMethod() {
TextView genderResult = (TextView) findViewById(R.id.genderText);
genderResult.setText("Cinsiyet:");
TextView calorieResult = (TextView) findViewById(R.id.remainCalorie);
String getGenderSTR = getIntent().getStringExtra("GENDER");
genderResult.setText(getGenderSTR);
String calorieResultSTR = getIntent().getStringExtra("CALORIECHOOSED");
calorieResult.setText(calorieResultSTR);
}
}
如果我重新安排我的 MainActivity.java 会是这样的...
public class MainActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
NecessaryThings showMyMethod = new NecassaryThings();
showMyMethod.myPersonalMethod();
/*
the rest of the codes...
*/
}
但如果我分离代码,它就不起作用了。为什么以及如何做?
最佳答案
public class MainActivity extends NecessaryThings {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
myPersonalMethod();
}
NecessaryThings 扩展了 Activity,因此 MainActivity 不再需要从 Activity 扩展,它应该从 NecessaryThings 扩展。我需要指出的一件事是 super.onCreate(savedInstanceState);将调用 onCreate();来自 NecessaryThings。由于我的 myPersonalMethod();来自父类(super class),你可以直接调用它。
关于java - Activity 的某些部分如何存储在 Android 的外部类中?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15080638/