【问题标题】:how to set intent action using value stored in string如何使用存储在字符串中的值设置意图操作
【发布时间】:2013-12-19 10:33:49
【问题描述】:

我想在我的应用程序中添加一项功能,用户可以在其中制作按钮以在设备上启动应用程序。现在,要进行设置,用户将输入他们想要调用的 Intent Action。如果用户输入“ACTION_MAIN”作为字符串值,是否可以在java中将其处理为Intent.ACTION_MAIN?

我知道使用地图可能是一种解决方案,但维护所有可用意图的详尽列表可能很麻烦。他们还有其他解决方案吗?字符串值可以引用变量吗?

【问题讨论】:

  • 你能举一个Java代码的例子你想如何处理Intent.ACTION_MAIN吗?

标签: java android android-intent


【解决方案1】:

假设用户定义的操作作为字符串值存储在userInput:

String userInput = "ACTION_MAIN";

使用reflection可以得到Intent.<ACTION_SOMETHING>的对应值,如下:

try {
    String action = (String) Intent.class.getDeclaredField(userInput).get(String.class);
    // use the action value here..
} catch (Exception e) {
    // no such action possible, maybe mistyped the action name
    e.printStackTrace();
}

示例:

String action = (String) Intent.class.getDeclaredField("ACTION_MAIN").get(String.class);

返回:

"android.intent.action.MAIN"

【讨论】:

  • 感谢 Amulya,这有帮助
猜你喜欢
  • 1970-01-01
  • 2018-09-25
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2023-01-20
  • 1970-01-01
相关资源
最近更新 更多