效果图:
layout;
<?xml version="1.0" encoding="utf-8"?> <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:id="@+id/activity_shared" android:layout_width="match_parent" android:layout_height="match_parent" tools:context="com.example.iamchan.allfunction.ui.widget.SharedActivity"> <LinearLayout android:orientation="vertical" android:layout_width="match_parent" android:layout_height="match_parent"> <TextView android:visibility="gone" android:padding="20dp" android:gravity="center" android:text="我是第一次" android:id="@+id/text" android:layout_width="match_parent" android:layout_height="wrap_content" /> <TextView android:visibility="gone" android:padding="20dp" android:gravity="center" android:text="我是第二次" android:id="@+id/text2" android:layout_width="match_parent" android:layout_height="wrap_content" /> <Button android:text="btn" android:id="@+id/btn" android:layout_width="match_parent" android:layout_height="wrap_content" /> </LinearLayout> </RelativeLayout>
java:
public class SharedActivity extends SwipeBackActivity { @BindView(R.id.text) TextView text; @BindView(R.id.text2) TextView text2; @BindView(R.id.btn) Button btn; private SharedPreferences sp; private SharedPreferences.Editor ed; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_shared); ButterKnife.bind(this); iniView(); initData(); } private void iniView() { sp = getSharedPreferences("tag", MODE_PRIVATE);//创建一个名为tag的share 模式为MODE_PRIVATE 只有自己程序能访问 其它程序不能访问 // 存在share中的数据都是以键值对的形式存在(这个需要放在方法中 刚开始我让sp = getSharedPreferences("tag", MODE_PRIVATE);作为属性初始化了) if (sp.getInt("cc", 0) == 0) { //判断cc是否存在(cc键名 0是不存在的返回值) 如果等于0了证明不存在 不存在就添加数据 ed = sp.edit(); //启用编辑 对于需要更改操作数据的都需要调用它(查询不用 上面那个就是查询 查询cc是否存在) ed.putInt("cc",1);//存数 键为cc 值为1 ed.commit();//操作完数据之后 需要提交 不提交就存不上 } } private void initData() { if (sp.getInt("cc", 0) == 1) {//获取cc(0为不存在时的返回值) 之前存了1 所以判断cc是否为1 为1向下执行 text.setVisibility(View.VISIBLE);//执行个操作 让一个text文本显示(默认为gone) ed = sp.edit();//启用编辑 ed.putInt("cc", 2);//存数 ed.commit();//提交 return;//跳出方法 } if (sp.getInt("cc", 0) == 2) {//第二次进入 text2.setVisibility(View.VISIBLE);//让text2显示(默认隐藏) return;//跳出方法 } } @OnClick(R.id.btn) public void onViewClicked() {//这是一个监听事件 ed=sp.edit();//启用编辑 ed.clear();//所有数据清除 ed.commit();//提交 //ed.remove("cc");//删除键为“cc”的数据 } }