已知界面,记录用户的姓名和年龄,输入姓名和年龄后,点击“写入数据”按钮,可以将姓名和年龄数据写入SharedPreferencesDemo数据文件suda share,点击“读取数据”按钮,则可以读现suda share文件中的信息。写出java代码即可,代码越少越好
时间: 2024-03-26 20:40:23 浏览: 18
好的,以下是代码:
```java
import android.content.SharedPreferences;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
import androidx.appcompat.app.AppCompatActivity;
public class MainActivity extends AppCompatActivity {
private EditText nameEditText, ageEditText;
private Button writeButton, readButton;
private SharedPreferences preferences;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
nameEditText = findViewById(R.id.edittext_name);
ageEditText = findViewById(R.id.edittext_age);
writeButton = findViewById(R.id.button_write);
readButton = findViewById(R.id.button_read);
preferences = getSharedPreferences("suda share", MODE_PRIVATE);
writeButton.setOnClickListener(v -> {
String name = nameEditText.getText().toString();
String age = ageEditText.getText().toString();
preferences.edit().putString("name", name).putString("age", age).apply();
Toast.makeText(this, "数据写入成功", Toast.LENGTH_SHORT).show();
});
readButton.setOnClickListener(v -> {
String name = preferences.getString("name", "");
String age = preferences.getString("age", "");
Toast.makeText(this, "姓名:" + name + ",年龄:" + age, Toast.LENGTH_SHORT).show();
});
}
}
```
这里使用了Lambda表达式来代替匿名内部类,代码量更少,更简洁。同时,使用了SharedPreferences.Editor的链式操作,使得代码更加简洁易读。
相关推荐
![docx](https://img-home.csdnimg.cn/images/20210720083331.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![docx](https://img-home.csdnimg.cn/images/20210720083331.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![doc](https://img-home.csdnimg.cn/images/20210720083327.png)
![docx](https://img-home.csdnimg.cn/images/20210720083331.png)
![docx](https://img-home.csdnimg.cn/images/20210720083331.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![docx](https://img-home.csdnimg.cn/images/20210720083331.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)