简体   繁体   English

如何在 Intent 中创建类变量: Intent intent = new Intent(getApplicationContext().this, variable.class);

[英]How do you make a class varible in an Intent: Intent intent = new Intent(getApplicationContext().this, variable.class);

I created a "Settings Activity" which has a radio button group with three buttons.我创建了一个“设置活动”,它有一个带有三个按钮的单选按钮组。 Each button is coded to pass a different string to sharedPreferences.每个按钮都被编码为将不同的字符串传递给 sharedPreferences。 Each string is the name of an Activity in the project.每个字符串都是项目中一个活动的名称。 1.) DollarActivity 2.) DynamicPercentActivity 3.) StaticPercentActivity 1.) DollarActivity 2.) DynamicPercentActivity 3.) StaticPercentActivity

(I used the Device File Explorer to confirm the string are being saved to sharedPreferences successfully) (我使用设备文件资源管理器确认字符串已成功保存到 sharedPreferences)

My idea was to retrieve the string data saved to sharePreferences and replace varActivity which forms part of the Intent below.我的想法是检索保存到 sharePreferences 的字符串数据并替换构成下面 Intent 的一部分的 varActivity。

Intent intent = new Intent(getApplicationContext().this, varActivity.class);
startActivity(intent);

I tried to create a variable "varActivity" which retieve the relevant string from sharedPreferences, however it did not work.我试图创建一个变量“varActivity”,它从 sharedPreferences 中检索相关字符串,但是它不起作用。 Android Studio prompted me to create class varActivity or innerclass varActivity or interface varActivity. Android Studio 提示我创建类 varActivity 或内部类 varActivity 或接口 varActivity。 I tried to the create class approach, however this effort created additions problems to be solved (public static void / public void compatibility issues between Activities).我尝试了创建类方法,但是这种努力产生了要解决的附加问题(活动之间的公共静态无效/公共无效兼容性问题)。

Is there some way retrieve the string from sharePreferences and replace varActivity with the new string data.有没有办法从 sharePreferences 中检索字符串并用新的字符串数据替换 varActivity。

There is no way to launch activity by name, but your task still can be implemented, if you put classes with their names in Map.无法按名称启动活动,但如果您将类及其名称放在 Map.xml 中,您的任务仍然可以实现。

Map<String, Class> activities = new HashMap<String, Class>() {{
    put("DollarActivity", DollarActivity.class);
    put("DynamicPercentActivity", DynamicPercentActivity.class);
    put("StaticPercentActivity", StaticPercentActivity.class);
}};
...
new Intent(this, activities.get(nameFromPreferences));

Anyway, I definitely recommend you to think again of the task you are trying to solve and find better solution.无论如何,我绝对建议您重新考虑您正在尝试解决的任务并找到更好的解决方案。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM