在 Android Studio 中“动态”传递字符串作为类名

问题描述 投票:0回答:6

假设你有一个字符串:

String string_name; //assign whatever value

你有一个意图:

Intent i = new Intent(getApplicationContext(), string_name.class);

这显然行不通。 AS 无法将 string_name 识别为类(尽管它作为主文件夹中的活动存在)。 forname 方法对我也不起作用(除非我做错了)。

我列出了 10 个活动/类,名称 1、名称 2、名称 3 等...完成每个活动后,程序会转到“转换”活动页面,然后在运行时重定向到下一个活动。因此,在用户完成 name1 活动后,程序会将其重定向到“转换”页面。之后我尝试将它们发送到 name2 活动。等等。

我想做的是将 name1、name2、活动的名称分配给“Transition”活动/类中的字符串(在本例中为string_name)。经过几行代码后,我成功检索了 name1 的名称,将其更改为 name2,并将其存储在字符串中。但 Android Studio 不接受“动态”字符串作为类值。

想法?

android android-intent
6个回答
3
投票

而不是这个:

Intent i = new Intent(getApplicationContext(), string_name.class);

你可以这样做:

Intent i = new Intent();
// Set the component using a String
i.setClassName(getApplicationContext(), string_name);

注意:确保您的所有活动均在清单中声明。


0
投票

更新: 您可以使用 Class.forName(String string_name)

String
获取类。但在
String
中,您必须给出该
class
的完整包名称。

    String string_name = "com.your_package.TestActivity";
    try {
        Class<?> classByName = Class.forName(string_name);
        Intent i = new Intent(this, classByName.class);
    } catch (ClassNotFoundException e) {
        Log.e("YourParentClassName", "System can't find class with given name: " + string_name);
    }

0
投票

看起来这个片段应该对您有帮助:

String string_name = "com.package.ActivityToStart";
Intent i = null;
try {
    i = new Intent(this, (Class<?>) Class.forName(string_name).newInstance());
} catch (ClassNotFoundException | InstantiationException | IllegalAccessException e) {
    Log.e("YourParentClassName", "System can't find class with given name: " + string_name, e);
}
if (i != null) {
    // do your work
}

0
投票

对于字符串到类名的转换,您需要正确给出包名称,否则它总是会抛出异常

String s = "yourclassname";
try {
  context.startActivity(new Intent(context, Class.forName("your.package.name." + s)));
} catch (ClassNotFoundException e) {
  Toast.makeText(context, s + " does not exist yet", Toast.LENGTH_SHORT).show();
}

0
投票

Class.forName() 用于创建 Class 类的对象。以下是语法:

Class c = Class.forName(String className)

上面的语句为作为字符串参数(className)传递的类创建了 Class 对象。请注意,参数 className 必须是要为其创建 Class 对象的所需类的完全限定名称。 java中任何类中返回相同类对象的方法也称为工厂方法。要为其创建 Class 对象的类名是在运行时确定的。


0
投票

我也有同样的问题!但该解决方案对我不起作用......:(

字符串类名=“MainActivity2”;

 public void buttonclick(){
     Intent intent = new Intent();
     intent.setClassName( getApplicationContext(), class_name);
startActivity(intent);
 }
© www.soinside.com 2019 - 2024. All rights reserved.