欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  移动技术

SharedPreferences使用demo

程序员文章站 2022-03-26 10:13:09
package com.example.helloworld;import android.annotation.SuppressLint;import android.content.SharedPreferences;import android.os.Bundle;import android.util.Log;import android.view.View;import android.widget.ArrayAdapter;import android.widget.ListVi...
package com.example.helloworld;

import android.annotation.SuppressLint;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import androidx.appcompat.app.AppCompatActivity;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentManager;
import androidx.fragment.app.FragmentTransaction;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

public class MyfragmentActivity extends AppCompatActivity {
    SimpleDateFormat sf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.myfragment);
        init1();
    }

    public void init1() {
        MyFragment2 f=new MyFragment2();
        Bundle b=new Bundle();
        b.putString("name","张三");
        f.setArguments(b);

        FragmentManager fm = getSupportFragmentManager();
        FragmentTransaction ft = fm.beginTransaction();

        ft.add(R.id.rl_fragment,f);
        ft.addToBackStack(null);
        ft.commit();

        findViewById(R.id.myfragment).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                SharedPreferences sp = getSharedPreferences("sp", MODE_PRIVATE);
                SharedPreferences.Editor edit = sp.edit();
                edit.putString("time", sf.format(new Date()));
                if(edit.commit()){
                    Toast.makeText(getApplicationContext(),"success",Toast.LENGTH_SHORT).show();
                }
            }
        });
        
        findViewById(R.id.rl_fragment).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                SharedPreferences sp = getSharedPreferences("sp",MODE_PRIVATE);
                String time = sp.getString("time", "--");
                TextView tv = findViewById(R.id.parent_textview_id);
                tv.setText(time+"");
            }
        });
    }

}

本文地址:https://blog.csdn.net/weixin_43292547/article/details/110558698

相关标签: android