SharedPreferences存储和对话框

  • SharedPreferences存储
  • 对话框
  • 后面的几个对话框
  • 单选对话框
  • 多选对话框
  • 等待对话框
  • 进度条对话框
  • 编辑对话框
  • 自定义对话框


SharedPreferences存储

在Android开发中,经常需要将少量简单类型数据保存在本地,如:用户设置。这些需要保存的数据可能一两个字符串,像这样的数据一般选择使用SharedPreferences来保存。

SharedPreferences:一个轻量级的存储类,特别适合用于保存软件配置参数。
(使用xml文件存放数据,文件存放在/data/data//shared_prefs目录下)

SharePreferences存储大小 sharedpreferences保存文件的路径_ide

使用SharedPreferences存储和读取数据的步骤
存储数据
保存数据一般分为四个步骤:

使用Activity类的getSharedPreferences方法获得SharedPreferences对象;
使用SharedPreferences接口的edit获得SharedPreferences.Editor对象;
通过SharedPreferences.Editor接口的putXXX方法保存key-value对;
通过过SharedPreferences.Editor接口的commit方法保存key-value对。
读取数据
读取数据一般分为两个步骤:

使用Activity类的getSharedPreferences方法获得SharedPreferences对象;
通过SharedPreferences对象的getXXX方法获取数据;

SharePreferences存储大小 sharedpreferences保存文件的路径_ide_02

<?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"
    tools:context=".MainActivity"
    android:orientation="vertical">

    <EditText
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:hint="姓名"
        android:id="@+id/edtName"/>

    <EditText
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:hint="年龄"
        android:id="@+id/edtAge"/>

    <RadioGroup
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="horizontal">

        <RadioButton
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="男"
            android:id="@+id/rbtBoy"/>
        <RadioButton
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="女"
            android:id="@+id/rbtGirl"/>
    </RadioGroup>

    <Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="保存"
        android:id="@+id/btnSave"/>

</LinearLayout>
package com.example.demo;

import androidx.appcompat.app.AppCompatActivity;

import android.content.SharedPreferences;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.RadioButton;
import android.widget.Toast;

public class MainActivity extends AppCompatActivity {
    private EditText edtName;
    private EditText edtAge;
    private RadioButton rbtBoy;
    private RadioButton rbtGirl;
    private Button btnSave;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        // 初始化组件
        initViews();

        // 从SP里面读取数据
        readFromSP();

        // new 空格  CTRL+SHIFT+空格
        btnSave.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String name = edtName.getText().toString();
                int age = Integer.parseInt(edtAge.getText().toString());
                boolean isBoy = rbtBoy.isChecked();

                // 保存数据到SP
                writeToSP(name, age, isBoy);
                Toast.makeText(MainActivity.this, "保存成功", Toast.LENGTH_SHORT).show();
            }
        });

    }

    /**
     * 保存个人信息到SP
     * @param name 姓名
     * @param age 年龄
     * @param isBoy 是否男
     */
    private void writeToSP(String name, int age, boolean isBoy) {
        SharedPreferences personInfo = getSharedPreferences("personInfo", MODE_PRIVATE);
        SharedPreferences.Editor edit = personInfo.edit();
        edit.putString("name", name);
        edit.putInt("age", age);
        edit.putBoolean("isBoy", isBoy);
        edit.commit();
    }

    /**
     * 初始化组件
     */
    private void initViews() {
        edtName = findViewById(R.id.edtName);
        edtAge = findViewById(R.id.edtAge);
        rbtBoy = findViewById(R.id.rbtBoy);
        rbtGirl = findViewById(R.id.rbtGirl);
        btnSave = findViewById(R.id.btnSave);
    }

    /**
     * 从SP里面读取代码 并显示
     */
    private void readFromSP() {
        SharedPreferences personInfo = getSharedPreferences("personInfo", MODE_PRIVATE);
        String name = personInfo.getString("name", "");
        int age = personInfo.getInt("age", 0);
        boolean isBoy = personInfo.getBoolean("isBoy", true);

        edtName.setText(name);
        edtAge.setText(String.valueOf(age));
        rbtBoy.setChecked(isBoy);
        rbtGirl.setChecked(!isBoy);
    }
}

对话框

SharePreferences存储大小 sharedpreferences保存文件的路径_xml_03

<?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"
    tools:context=".MainActivity"
    android:orientation="vertical">

    <Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="普通对话框"
        android:id="@+id/btn1"/>

    <Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="三个按钮对话框"
        android:id="@+id/btn2"/>
    <Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="列表对话框"
        android:id="@+id/btn3"/>

</LinearLayout>
package com.example.dialog;

import androidx.appcompat.app.AppCompatActivity;

import android.app.AlertDialog;
import android.app.Dialog;
import android.content.DialogInterface;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;

public class MainActivity extends AppCompatActivity {
    private Button btn1;
    private Button btn2;
    private Button btn3;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        btn1 = findViewById(R.id.btn1);
        btn1.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                new AlertDialog.Builder(MainActivity.this)
                        .setMessage("成绩超过60了吗")
                        .setTitle("问候")
                        .setPositiveButton("确定", new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                Toast.makeText(MainActivity.this, "恭喜及格",Toast.LENGTH_SHORT).show();
                            }
                        })
                        .setNegativeButton("没有", new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                Toast.makeText(MainActivity.this, "遗憾挂科",Toast.LENGTH_SHORT).show();
                            }
                        })
                        .show();
            }
        });

        btn2 = findViewById(R.id.btn2);
        btn2.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                new AlertDialog.Builder(MainActivity.this)
                        .setMessage("你喜欢哪个明星")
                        .setTitle("请选择")
                        .setPositiveButton("贾玲", new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                Toast.makeText(MainActivity.this, "您选择了贾玲",Toast.LENGTH_SHORT).show();
                            }
                        })
                        .setNegativeButton("沈腾", new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                Toast.makeText(MainActivity.this, "您选择了沈腾",Toast.LENGTH_SHORT).show();
                            }
                        })
                        .setNeutralButton("华晨宇", new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                Toast.makeText(MainActivity.this, "您选择了华晨宇",Toast.LENGTH_SHORT).show();
                            }
                        })
                        .show();
            }
        });

        btn3 = findViewById(R.id.btn3);
        btn3.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String[] classes = {"19软工1班","19软工2班","19软工3班","19软工4班"};
                new AlertDialog.Builder(MainActivity.this)
                        .setTitle("请选择你在哪个班级")
                        .setItems(classes, new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                Toast.makeText(MainActivity.this,"您在"+classes[which],
                                        Toast.LENGTH_SHORT).show();
                            }
                        })
                        .show();
            }
        });

    }
}

后面的几个对话框

<?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"
    tools:context=".MainActivity"
    android:orientation="vertical">

    <Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="单选对话框"
        android:id="@+id/btn4"/>

    <Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="多选对话框"
        android:id="@+id/btn5"/>
    <Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="等待对话框"
        android:id="@+id/btn6"/>
    <Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="进度对话框"
        android:id="@+id/btn7"/>
    <Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="编辑对话框"
        android:id="@+id/btn8"/>
    <Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="自定义对话框"
        android:id="@+id/btn9"/>

</LinearLayout>
package com.example.demo;

import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;

import android.content.DialogInterface;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;

public class MainActivity extends AppCompatActivity {
    private Button btn4;
    private Button btn5;
    private Button btn6;
    private Button btn7;
    private Button btn8;
    private Button btn9;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        btn4 = findViewById(R.id.btn4);
        btn5 = findViewById(R.id.btn5);
        btn6 = findViewById(R.id.btn6);
        btn7 = findViewById(R.id.btn7);
        btn8 = findViewById(R.id.btn8);
        btn9 = findViewById(R.id.btn9);
    }
}

单选对话框

btn4.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String[] classes = {"19软工1班", "19软工2班", "19软工3班", "19软工4班"};

                new AlertDialog.Builder(MainActivity.this)
                        .setTitle("请选择班级")
                        .setSingleChoiceItems(classes, -1, new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                Toast.makeText(MainActivity.this, "您来自" + classes[which], Toast.LENGTH_SHORT).show();
//                                dialog.cancel();
                            }
                        })
                        .setPositiveButton("确定", new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                dialog.cancel();
                            }
                        })
                        .show();
            }
        });

多选对话框

btn5.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                String[] likes = {"写代码", "跑步", "音乐", "篮球"};
                boolean[] checked = {false, false, false, false};
                new AlertDialog.Builder(MainActivity.this)
                        .setMultiChoiceItems(likes, null, new DialogInterface.OnMultiChoiceClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which, boolean isChecked) {
                                Log.e("MultiChoice", "which = " + which + " isChecked = " + isChecked);
                                checked[which] = isChecked;
                            }
                        })
                        .setPositiveButton("确定", new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                StringBuffer stringBuffer = new StringBuffer();
                                stringBuffer.append("您的爱好是");
                                for(int i=0; i<checked.length; i++){
                                    if(checked[i]){
                                        stringBuffer.append(likes[i]).append(",");
                                    }
                                }
                                Toast.makeText(MainActivity.this, stringBuffer.toString(), Toast.LENGTH_SHORT).show();
                                dialog.cancel();
                            }
                        })
                        .show();
            }
        });

等待对话框

btn6.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                ProgressDialog dialog = new ProgressDialog(MainActivity.this);
                dialog.setTitle("正在登录...");
                dialog.setCancelable(false);
                dialog.show();
            }
        });

进度条对话框

btn7.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                ProgressDialog dialog = new ProgressDialog(MainActivity.this);
                dialog.setTitle("正在下载。。。");
                dialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
                dialog.setMax(100);
                dialog.show();

                new Thread(new Runnable() {
                    @Override
                    public void run() {
                        int progress = 0;
                        while(progress <= 100){
                            progress++;
                            try {
                                Thread.sleep(100);
                            } catch (InterruptedException e) {
                                e.printStackTrace();
                            }
                            dialog.setProgress(progress);
                        }
                        dialog.cancel();
                    }
                }).start();
            }
        });

编辑对话框

btn8.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                EditText editText = new EditText(MainActivity.this);
                new AlertDialog.Builder(MainActivity.this)
                        .setTitle("请输入姓名")
                        .setView(editText)
                        .setPositiveButton("确定", new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                String name = editText.getText().toString();
                                Toast.makeText(MainActivity.this, "你好"+name,
                                        Toast.LENGTH_SHORT).show();
                            }
                        })
                        .show();
            }
        });

自定义对话框

添加布局文件dialog_layout.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"
    tools:context=".MainActivity"
    android:orientation="vertical">

    <EditText
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:id="@+id/edt_name"/>

    <EditText
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:id="@+id/edt_age"/>

</LinearLayout>

使用布局文件

btn9.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                View view = LayoutInflater.from(MainActivity.this)
                        .inflate(R.layout.dialog_layout, null, false);
                EditText edtName = view.findViewById(R.id.edt_name);
                EditText edtAge = view.findViewById(R.id.edt_age);

                new AlertDialog.Builder(MainActivity.this)
                        .setTitle("请输入姓名和年龄")
                        .setView(view)
                        .setPositiveButton("确定", new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                String name = edtName.getText().toString();
                                int age = Integer.parseInt(edtAge.getText().toString());

                                Toast.makeText(MainActivity.this, "你好"+name + "年龄"+ age,
                                        Toast.LENGTH_SHORT).show();
                            }
                        })
                        .show();
            }
        });