public class MainActivity extends Activity {
private EditText et;
private Button bt;
private TextView tv;
SharedPreferences preferences;
SharedPreferences.Editor editor;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
et = (EditText) findViewById(R.id.editText1);
bt = (Button) findViewById(R.id.button1);
tv = (TextView) findViewById(R.id.textView1);
preferences = getSharedPreferences("crazyit", MODE_WORLD_READABLE);
editor = preferences.edit();
bt.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View arg0) {
// 读取字符串
String time = preferences.getString("time", null);
int randNum = preferences.getInt("random", 0);
String result = time == null ? "您暂时还未写入数据" : "写入的时间为" + time
+ "\n 上次生成的随机数是" + randNum;
Toast.makeText(MainActivity.this, result, Toast.LENGTH_SHORT).show();
}
});
tv.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
SimpleDateFormat adf = new SimpleDateFormat("yyyy年MM月dd日 hh:mm:ss");
editor.putString("time", adf.format(new Date()));
editor.putInt("random", (int)(Math.random()*100));
editor.commit();
}
});
}
}