如何使用字符串中的类名启动新的 android 活动? [英] How can I start a new android activity using class name in a string?

查看:24
本文介绍了如何使用字符串中的类名启动新的 android 活动?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在处理的 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) {
}

编辑

这里的类名将是带有包名的类的全名.例如,如果您的包名称为 xyz 并且您的活动名称为 A,则活动 A 的全名将是 xyzA.

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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆