package com.example.thirteen;
import android.app.Activity;
import android.content.Context;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.Toast;
/**
* @author HD
* @date 2015-12-7
* @package_name com.example.thirteen
* @file_name MainActivity.java
*/
public class MainActivity extends Activity implements OnClickListener {
private Button btnAddData;
private Button btnReceiveData;
private Button btnClearData;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
btnAddData = (Button) findViewById(R.id.btnAddData);
btnReceiveData = (Button) findViewById(R.id.btnReceiveData);
btnClearData = (Button) findViewById(R.id.btnClearData);
btnAddData.setOnClickListener(this);
btnReceiveData.setOnClickListener(this);
btnClearData.setOnClickListener(this);
}
@Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.btnAddData:
SharedPreferences.Editor editor = getSharedPreferences(
"MyFirstSharedPre", Context.MODE_PRIVATE).edit();
editor.putString("jjj", "chenlong");
editor.commit();
break;
case R.id.btnReceiveData:
SharedPreferences sharedPreferences = getSharedPreferences(
"MyFirstSharedPre", Context.MODE_PRIVATE);
String name = sharedPreferences.getString("name", null);
int age = sharedPreferences.getInt("age", 0);
Toast.makeText(MainActivity.this,
"name is" + name + "/n" + "age is" + age,
Toast.LENGTH_SHORT).show();
break;
case R.id.btnClearData:
SharedPreferences.Editor editor2 = getSharedPreferences(
"MyFirstSharedPre", Context.MODE_PRIVATE).edit();
editor2.putString("jjj", "chenlong");
editor2.clear();
editor2.commit();
}
}
}
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
tools:context="com.example.thirteen.MainActivity" >
<Button
android:id="@+id/btnAddData"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:layout_centerVertical="true"
android:text="Button" />
<Button
android:id="@+id/btnReceiveData"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignLeft="@+id/btnAddData"
android:layout_below="@+id/btnAddData"
android:layout_marginTop="64dp"
android:text="获取数据" />
<Button
android:id="@+id/btnClearData"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignLeft="@+id/btnReceiveData"
android:layout_alignParentBottom="true"
android:layout_marginBottom="16dp"
android:text="清除数据" />
</RelativeLayout>