SharedPreferences使用demo
程序员文章站
2022-06-24 12:26:10
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
上一篇: 浅谈MySQL event 计划任务
下一篇: 11.26