SP的保存与显示:
xml:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:padding="15dp"
tools:context=".datastorage.SharedPreferencesActivity">
<EditText
android:id="@+id/et_name"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="输入内容" />
<Button
android:id="@+id/btn_save"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="10dp"
android:text="保存" />
<Button
android:id="@+id/btn_show"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="10dp"
android:text="显示" />
<TextView
android:id="@+id/tv_content"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="10dp"/>
</LinearLayout>
activity:
package com.example.lineralayout.datastorage;
import androidx.appcompat.app.AppCompatActivity;
import android.app.backup.SharedPreferencesBackupHelper;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import com.example.lineralayout.R;
public class SharedPreferencesActivity extends AppCompatActivity {
private EditText mEtName;
private Button mBtnSave,mBtnShow;
private TextView mTvContent;
private SharedPreferences mSharedPreferences;
private SharedPreferences.Editor mEditor;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_shared_preferences);
mSharedPreferences = getSharedPreferences("data",MODE_PRIVATE);
mEditor = mSharedPreferences.edit();
mEtName = findViewById(R.id.et_name);
mBtnSave = findViewById(R.id.btn_save);
mBtnShow = findViewById(R.id.btn_show);
mTvContent = findViewById(R.id.tv_content);
mBtnSave.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
//获取EditText里面的内容
mEditor.putString("name",mEtName.getText().toString());
//提交
mEditor.apply();
}
});
mBtnShow.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
mTvContent.setText(mSharedPreferences.getString("name",""));
}
});
}
}
点击查看更多内容
1人点赞
评论
共同学习,写下你的评论
评论加载中...
作者其他优质文章
正在加载中
感谢您的支持,我会继续努力的~
扫码打赏,你说多少就多少
赞赏金额会直接到老师账户
支付方式
打开微信扫一扫,即可进行扫码打赏哦