如何在字符串中使用类名启动新的android活动? [英] How can I start a new android activity using class name in a string?
问题描述
我正在处理的android应用程序有问题.
I'm having a problem with an android application that I'm working on.
我的应用程序有几个部分,下一个加载的屏幕基于一个字符串.因此,第1部分的屏幕1将是S1S1.
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.
我的问题是,我如何才能基于字符串开始一项活动.我将S1S1保存在字符串中,让我们将其称为下一个活动.无需键入S1S1.class,我需要它来自字符串.我已经尝试了所有我能想到的东西,而Google并没有太大帮助.
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.
我尝试过的一些事情
Intent myIntent = new Intent(nextactivity);
Intent myIntent = new Intent(v.getContext(), getClass().getName().valueOf(nextactivity));
Intent myIntent = new Intent(v.getContext(), Class.forName(nextactivity));
并尝试与
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) {
}
编辑
这里的类名将是带有包名的类的全名.
例如,如果包名称为x.y.z
,并且活动名称为A
,则活动A
的全名将为x.y.z.A
.
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
.
这篇关于如何在字符串中使用类名启动新的android活动?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!