我创建了一个登录页面,用户只需输入他们的用户名(不需要密码或身份验证),它将显示在下一个活动中。但是每次打开应用程序时,您都必须输入用户名。我如何让它记住用户名。(语言-Java)
谢谢!
(我是初学者)
package com.example.app;
import androidx.appcompat.app.AppCompatActivity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
public class MainActivity extends AppCompatActivity {
Button btn;
EditText et;
String st;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
btn= findViewById(R.id.button);
et=findViewById(R.id.edittext);
btn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Intent i=new Intent(MainActivity.this, Welcome.class);
st=et.getText().toString();
i.putExtra("Value",st);
startActivity(i);
finish();
Run Code Online (Sandbox Code Playgroud)
(这是用户输入用户名的活动)
package com.example.app;
import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.TextView;
public class Welcome extends AppCompatActivity {
TextView tv;
String st;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_welcome);
tv=findViewById(R.id.textView);
st=getIntent().getExtras().getString("Value");
tv.setText(st);
}
}
Run Code Online (Sandbox Code Playgroud)
(这是欢迎活动)
我认为您需要将用户名保存在 Sharedpreferences 中,然后当您启动应用程序时,从 sharedpreferences 获取值并检查该值是否为 null 或为空,然后让用户输入他的用户名,否则您可以从 sharedpreferences 设置用户名。
试试这个代码:
///save sharedpreferences
SharedPreferences sharedPreferences =
getSharedPreferences("prefs",Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putString("username","put here your username");
editor.apply();
///get sharedpreferences
SharedPreferences sharedPreferences1 =
getSharedPreferences("prefs",Context.MODE_PRIVATE);
String username = sharedPreferences1.getString("username","");
tv.setText(username);
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
50 次 |
| 最近记录: |