开发者

How can I start a new android activity using class name in a string?

I'm having a problem with an android application that I'm working on.

My application has several sections and the next screen that loads is based on a string开发者_JAVA技巧. So, screen 1 of section 1 would be, S1S1.

My question is, how can I start an activity based on a string. I have S1S1 saved in a string, let us call it next activity. Rather than having to type S1S1.class, I need it to come from the string. I've tried everything I can think of and google hasn't helped much.

Some things I've tried are

Intent myIntent = new Intent(nextactivity);
Intent myIntent = new Intent(v.getContext(), getClass().getName().valueOf(nextactivity));
Intent myIntent = new Intent(v.getContext(), Class.forName(nextactivity));

and tried running with

startActivityForResult(myIntent, 0); 

but nothing seems to work. Any ideas?


Here is a code by which you can start activity using the name of the activity

String activityToStart = "com.example.MainActivity";
try {
    Class<?> c = Class.forName(activityToStart);
    Intent intent = new Intent(this, c);
    startActivity(intent);
} catch (ClassNotFoundException ignored) {
}

EDIT

Here class name will be full name of the class with the package name. For example if your package name will be x.y.z and if you have Activity name called A then the full name of the Activity A will be x.y.z.A.


An even better way (and one that is used in the system to launch Browser.apk along with other apps that aren't bundled with AOSP):

Intent intent = new Intent();
intent.setClassName("com.android.browser","com.android.BrowserActivity");

context.startActivity(intent);

Alternatively, if you want to check that you can start the Activity from the command line, you can do something like this from your shell:

adb shell
am start com.android.browser/.BrowserActivity


I am not aware of solution but i have an alternative.. the way similar to div hide and show in web pages.

if your s1s1 is to loaded low content have them in a linearlayout and keep their visibility gone on loading form s1. when you click on s1 to reach s1s1 hide s1 and set the params of visibility to "visible".

By doing this you can avoid creating a separate activity and this way is also easy to navigate back.


Use Enums!

public enum SectionActivity {

  S1S1(MyS1Activity.class),
  S1S2(S2Activity.class);

  private Class<? extends Activity> activityClass;

  private SectionActivity(Class<? extends Activity> clazz) {

   this.activityClass = clazz;
  }

  public Class<? extends Activity> getActivity {
     return activityClass;
  }    
}

Then somewhere in your code:

SectionActivity act = SectionActivity.valueOf(string);
Intent intent = new Intent(this, act.getActivity());
startActivity(intent);
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜