Reputation: 4914
code reuse for activity is confusing. In normal situation we can design a parent activity and put all common method in it. like follow :
public class BaseActivity extends Activity{
@Override
protected void doExit() {
showDialog(DIALOG_EXIT_ALTER);
}
protected Dialog onCreateDialog(int id, Bundle args) {
switch (id) {
case DIALOG_EXIT_ALTER:
return new AlertDialog.Builder(BaseUIActivity.this)
.setTitle("Exit?")
.setPositiveButton("Yes",
new DialogInterface.OnClickListener() {
public void onClick(
DialogInterface dialoginterface, int i) {
close();
}
})
.setNeutralButton("No",null).create();
default:
return null;
}
}
protected void close() {
finish();
}
}
then other activities extend BaseActivity will show a alertdialog instead of exit immediately when back button press. But in android framework there are more than one build-in activites such like PreferenceActivity,ListActivity,ActivityGroup,etc.
if my activity extend those activities then it can't use the common code defined in BaseActivity.because of Java's single inheritance. So is there other way recommend to do code reuse for activity in android?
Upvotes: 2
Views: 2055
Reputation: 499
Create a new class ActivityHelper.
public class ActivityHelper { Activity activity; public ActivityHelper(Activity activity) { this.activity = activity; } public Dialog onCreateDialog(int id, Bundle args) { // do many usefull things return result; } }
Use it in all your activities.
protected Dialog onCreateDialog(int id, Bundle args) { return activityHelper(id, args); }
Upvotes: 2
Reputation: 37729
Since PreferenceActivity
, ListActivity
, ActivityGroup
are specialized form of Activity
, and you have to use them in their relative context.
So IMHO workaround is to have one copy of Base
+[all above Activity
] if you have to use them more then one time in your project, and extend your child ListActivity
or whatever Specialized Activity
it is.
Upvotes: 1