【问题标题】:Cannot Fire intent by casting string to class无法通过将字符串转换为类来触发意图
【发布时间】:2013-01-16 00:28:04
【问题描述】:

我创建了一个 Listview 表单,我想为特定类触发意图。这里 var:position 是我点击的 ListView 行的位置。无论所有同一个包中的活动和正确的名称。

String[] slideMenuOptions = {"CarGallery.class","connectus.class","BookService.class"};
String str = slideMenuOptions[position];
Class <?> c = Class.forName(str);
Intent intent = new Intent(context,c);
context.startActivity(intent);

【问题讨论】:

  • 从字符串中删除.class。 String 值被解释为类名的文字表示。
  • 还是同样的问题 java.lang.ClassNotFoundException.
  • new Intent(context,c.class); ?
  • 来自一个我恰好正在从事的项目。这段代码已经工作了几个月。 thisClass = Class.forName(context.getPackageName() + "." + thisDict.getClassName();) 这提醒我 Class.forName 需要完全限定的包名。

标签: android class android-intent


【解决方案1】:

使用不带 .class 的类的全名来获取类名并启动下一个 Activity 为:

String[] slideMenuOptions = {"xx.xxx.CarGallery",
                             "xx.xxx.connectus",
                             "xx.xxx.BookService"};
String str = slideMenuOptions[position];
Class <?> c = Class.forName(str);
Intent intent = new Intent(context,c);
context.startActivity(intent);

确保您已在androidmanifest.xml 文件中声明所有活动

【讨论】:

    【解决方案2】:
    您需要提供完整的限定类名。 
    例如,如果您的 CarGallery.class 具有包
    那么您应该提供 CarGaller 类以及包名称。
    com.tech.CarGaller。
    我使用了以下代码。它对我来说很好。如果您有任何问题,请告诉我。

    /*String[] slideMenuOptions = {"com.tech.CarGallery","com.tech.connectus","com.tech.BookService"};*/
    String[] slideMenuOptions = {"xx.xxx.CarGallery ","xx.xxx.connectus","xx.xxx.BookService"};
    String str = slideMenuOptions[1];
    Class c = Class.forName(str);
    System.out。 println("获取类名"+c.getName());
    Intent intent = new Intent(context,c);
    context.startActivity(intent);

    【讨论】:

      猜你喜欢
      • 2023-03-23
      • 1970-01-01
      • 2014-07-31
      • 2016-03-11
      • 1970-01-01
      • 2013-03-09
      • 2018-01-13
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多