Android Studio 在Kotlin中将字符串作为活动的Intent

kognpnkq  于 2023-01-13  发布在  Android
关注(0)|答案(1)|浏览(172)

我尝试根据sharedpreference字符串中的内容启动一个Activity,这样我就可以使用1个登录页面,根据我单击的按钮重定向到相应的Activity。这里我在sharedpref中输入了Activity的名称,即ConfigureActivity。

sharedSettingsData.edit()
                .putString("settingsLogin", "ConfigureActivity")
                .apply()

然后在这里我获取sharedpref中的内容,并将其插入到一个变量中:

val activityHandler = sharedSettingsData.getString("settingsLogin","").toString()

这里我试着启动它

val intent = Intent(this, activityHandler::class.java)
            startActivity(intent)

但在执行此操作时,我得到这个错误:

android.content.ActivityNotFoundException: Unable to find explicit activity class {com.example.myapp/java.lang.String};
rn0zuynd

rn0zuynd1#

我用这个解决了我的问题:

try {
                if(sharedSettingsData.getString("settingsLogin", "") == "ConfigureActivity"){
                    val i = Intent(this, ConfigureActivity::class.java)
                    startActivity(i)
                    overridePendingTransition(R.anim.slide_in_right, R.anim.slide_out_left)
                }
                if(sharedSettingsData.getString("settingsLogin", "") == "SettingsChangePin"){
                    val i = Intent(this, SettingsChangePin::class.java)
                    startActivity(i)
                    overridePendingTransition(R.anim.slide_in_right, R.anim.slide_out_left)
                }
                if(sharedSettingsData.getString("settingsLogin", "") == "ConnectionsActivity"){
                    val i = Intent(this, ConnectionsActivity::class.java)
                    startActivity(i)
                    overridePendingTransition(R.anim.slide_in_right, R.anim.slide_out_left)
                }
                if(sharedSettingsData.getString("settingsLogin", "") == "InfoActivity"){
                    val i = Intent(this, InfoActivity::class.java)
                    startActivity(i)
                    overridePendingTransition(R.anim.slide_in_right, R.anim.slide_out_left)
                }
            }
            catch (e: Exception){
                Log.d("[ACTIVITY EXCEPTION]", "Unable to find correct activity to intent to. Code: $e")
            }

相关问题