Android:如何仅在Kotlin中首次显示屏幕?
我的应用程序有一个初始屏幕(活动),要求用户输入他们的姓名,然后单击登录按钮。用户执行此操作后,我不希望应用程序再次显示此屏幕,相反,应用程序应该启动另一个活动。我做了一些研究,发现你应该使用共享偏好,但我仍然感到困惑。以下是初始屏幕活动的代码:Android:如何仅在Kotlin中首次显示屏幕?,android,kotlin,sharedpreferences,Android,Kotlin,Sharedpreferences,我的应用程序有一个初始屏幕(活动),要求用户输入他们的姓名,然后单击登录按钮。用户执行此操作后,我不希望应用程序再次显示此屏幕,相反,应用程序应该启动另一个活动。我做了一些研究,发现你应该使用共享偏好,但我仍然感到困惑。以下是初始屏幕活动的代码: class StudentNameInput : AppCompatActivity(), View.OnClickListener { override fun onCreate(savedInstanceState: Bundle?) {
class StudentNameInput : AppCompatActivity(), View.OnClickListener {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_student_name_input)
btnStudentLogIn.setOnClickListener(this)
}
private fun validate(): Boolean {
if (txt_student_name.text.toString().isEmpty()){
txt_student_name.error = "Name cannot be empty"
return false
}
return true
}
override fun onClick(v: View?){
when(v?.id){
R.id.btnStudentLogIn->{
if(validate()){
Log.i(null, "setOnClickListener")
val intent = Intent(this, StudentInitialActivity::class.java)
startActivity(intent)
}
}
}
}
您应该将用户名保存在“共享首选项”中,然后在启动活动时需要检查“共享首选项”是否已保存用户名,如果是,则启动下一个活动并完成当前活动,如果否,则保留当前活动,如下所示:
class StudentNameInput : AppCompatActivity(), View.OnClickListener {
private lateinit var sharedPref: SharedPreferences
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
sharedPref: SharedPreferences = getSharedPreferences("YOUR_PREF_NAME", Context.MODE_PRIVATE)
if (wasUserNameSaved()) {
val intent = Intent(this, StudentInitialActivity::class.java)
startActivity(intent)
finish()
return
}
setContentView(R.layout.activity_student_name_input)
btnStudentLogIn.setOnClickListener(this)
}
private fun validate(): Boolean {
if (txt_student_name.text.toString().isEmpty()){
txt_student_name.error = "Name cannot be empty"
return false
}
return true
}
override fun onClick(v: View?){
when(v?.id){
R.id.btnStudentLogIn->{
if(validate()){
Log.i(null, "setOnClickListener")
sharedPref.edit().putString("user_name", txt_student_name.text.toString()).apply()
val intent = Intent(this, StudentInitialActivity::class.java)
startActivity(intent)
}
}
}
}
private fun wasUserNameSaved(): Boolean {
return sharedPref.getString("user_name", "").isNotEmpty()
}
对不起,格式错误,我是从手机上写的