Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
302 views
in Technique[技术] by (71.8m points)

java - 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. 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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...