【问题标题】:Use SharedPreferences to set the class value for an intent使用 SharedPreferences 设置意图的类值
【发布时间】:2016-11-28 21:15:29
【问题描述】:

我的应用程序中的一个屏幕有一个按钮,可将用户带到另一个屏幕。目标屏幕由存储在 SharedPreferences 中的首选项确定。如何从共享偏好设置 Intent 的类?

这是我目前拥有的按钮:

case R.id.favoriteButton1:
                final Intent favorite1Screen = new Intent();
                favorite1Screen.setClass(this, prefs.getString("favorite1Class", ""));
                startActivity(favorite1Screen);
                break;

这是可以设置该首选项的屏幕之一: 案例 R.id.action_favorite_1:

            final SharedPreferences prefs2 = getSharedPreferences("myDataStorage", MODE_PRIVATE);
            final SharedPreferences.Editor nEditor = prefs2.edit();

            nEditor.putString("favorite1Text", "Job Hazard Analysis");
            nEditor.putString("favorite1Color", "Safety");
            nEditor.putString("favorite1Intent", "Job_Hazard_Analysis");
            nEditor.commit();

            break;

intent 显然不接受字符串值来设置其类,有没有办法让这个工作?

【问题讨论】:

  • 我不推荐这个。使用外部输入直接创建类名会引发安全问题。使用某种验证逻辑将您的字符串映射到 Java Class(例如,静态 HashMap<String, Class>),以便能够忽略意外值。

标签: android android-intent sharedpreferences


【解决方案1】:

您甚至可以像这样从 Intent 构造函数设置上下文和类:

Intent intent = new Intent(this, YourClass.class);

不过,您可以继续使用 setClass 方法。我认为错误可能在于类引用的解释方式。

我认为您的类名字符串可能必须是完全限定的类名。意味着包和所有必须明确。喜欢:

`com.mypackage.myclass_name`

然后,一旦您在“共享首选项”中拥有该选项,您就可以尝试:

Intent intent = new Intent(this, 'com.mypackage.myclass_name');

或者如果这不起作用尝试:

Intent intent = new Intent(this, Class.forName('com.mypackage.myclass_name'));

【讨论】:

  • 我已经尝试了所有这些方法,但问题仍然存在,它不接受字符串作为分配类名的有效输入法。
  • 抱歉,我犯了一个简单的错误,实际上确实解决了问题。
  • @xander 很高兴知道。祝你好运。
猜你喜欢
  • 2011-03-20
  • 1970-01-01
  • 1970-01-01
  • 2014-06-02
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2022-12-04
  • 1970-01-01
相关资源
最近更新 更多