0

In order to simplify some code, I'm wondering if it is possible to parameterize code that launches activities in an android application, so that instead of having 5

    public void showSettings(View view) {
    Intent SettingsActivity = new Intent(MainActivity.this, Settings.class);
    startActivity(SettingsActivity);

I can do something like the following

 public void showActivity(View view, String ActivityName) {
        Intent ActivityName = new Intent(MainActivity.this, ActivityName.class);
        startActivity(ActivityName);

Then, for each button in the UI, I simply apply the following to the "onclick" event

showActivity(Settings);

or

showActivity(domains);

This would save about 40-50 lines of code in my app. Obviously I know the above code is incorrect, but I'm not sure if it's possible to do what I'm trying to accomplish.

4

2 に答える 2

2

次のようなものはどうですか?

public <T> void showActivity(View view, Class<T> activity) {
    Intent activityName = new Intent(MainActivity.this, activity);
    startActivity(activityName);
}

あなたはそれを呼び出すことができます

showActivity(Settings.class);
于 2012-05-22T23:42:55.627 に答える
1

I'd recommend use ACTIONs (String) instead of specifying exactly context and class. This way you even can share activities among applications, and if you decide to switch to different activity class, you can edit only android manifest, instead of editing all java source code calls this activity.

于 2012-05-23T00:29:36.293 に答える