您的位置:首页 > Web前端

SharedPreferences应用之首次加载引导界面

2017-05-24 09:59 211 查看
今天来讲一下SharedPreferences最基本的使用,话不多说直接上代码:

//入口程序为欢迎界面
public class WelcomActivity extends Activity {

@Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_welcome);
// 欢迎界面,启动后,延迟2秒,跳转
new Thread() {
public void run() {
SystemClock.sleep(2000);
// 判断,跳转
if (isFirstRun()) {
// 跳转到引导
Intent intent = new Intent(WelcomActivity.this,
SlpashActivity.class);
startActivity(intent);
} else {
// 跳转到主界面
Intent intent = new Intent(WelcomActivity.this,
MainActivity.class);
startActivity(intent);
}
// 跳转后,结束当前Activity
finish();
};
}.start();
// 如果是第一次启动,跳转到引导界面
// 如果 不是第一次启动,跳转到主界面
}

/**
* 原理:
*
* 从共享参数中,读取一个值,如果该值有内容,说明已经启动过,如果没有值,是第一次启动
*
* @return
*/
private boolean isFirstRun() {
// 读Shared
SharedPreferences shared = getSharedPreferences("first", MODE_PRIVATE);
return shared.getBoolean("isFirst", true);
}

}
//引导界面
package com.example.day012_firstrundemo;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.TextView;

public class SlpashActivity extends Activity {

@Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
// 创建一个TextView
TextView tv = new TextView(this);
tv.setText("引导界面");
setContentView(tv);
tv.setOnClickListener(new OnClickListener() {

@Override
public void onClick(View v) {
// 点击跳转到主界面
Intent intent = new Intent(SlpashActivity.this,
MainActivity.class);
startActivity(intent);
finish();

}
});
}
}
//主界面
public class MainActivity extends Activity {

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// 如果程序进行到这里,说明第一次启动完成
// 向共享参数中,写入一个boolean为false的值,与Welcome界面中读取一致
SharedPreferences shared = getSharedPreferences("first", MODE_PRIVATE);
Editor editor = shared.edit();
editor.putBoolean("isFirst", false);
editor.commit();

}

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息