简体   繁体   中英

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. Each string is the name of an Activity in the project. 1.) DollarActivity 2.) DynamicPercentActivity 3.) StaticPercentActivity

(I used the Device File Explorer to confirm the string are being saved to sharedPreferences successfully)

My idea was to retrieve the string data saved to sharePreferences and replace varActivity which forms part of the Intent below.

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. Android Studio prompted me to create class varActivity or innerclass varActivity or interface 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.

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<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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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