视图代码:
<LinearLayout 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:orientation="vertical"
tools:context=".MainActivity" >
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/username" />
<EditText
android:id="@+id/edit1"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/age" />
<EditText
android:id="@+id/edit2"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="horizontal" >
<Button
android:id="@+id/button1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/buttontext1" />
<Button
android:id="@+id/button2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/buttontext2" />
</LinearLayout>
</LinearLayout>
java类:
package com.example.chucuncanshu;
import android.R.integer;
import android.os.Bundle;
import android.app.Activity;
import android.content.Context;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
public class MainActivity extends Activity {
EditText edit1;
EditText edit2;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button btn1 = (Button) findViewById(R.id.button1);
Button btn2 = (Button) findViewById(R.id.button2);
edit1 = (EditText) findViewById(R.id.edit1);
edit2 = (EditText) findViewById(R.id.edit2);
ButtonOnClickListener bclick=new ButtonOnClickListener();
btn1.setOnClickListener(bclick);
btn2.setOnClickListener(bclick);
}
private final class ButtonOnClickListener implements View.OnClickListener{
@Override
public void onClick(View v) {
SharedPreferences sharedperferences = MainActivity.this
.getSharedPreferences("user",Context.MODE_WORLD_READABLE);
switch (v.getId()){
case R.id.button1:
String username = edit1.getText().toString();
int age = Integer.valueOf(edit2.getText().toString());
Editor editor = sharedperferences.edit();
editor.putString("username", username);
editor.putInt("age", age);
editor.commit();
Toast.makeText(getBaseContext(), R.string.sucess1, 1).show();
break;
case R.id.button2:
String username1=sharedperferences.getString("username", "无名氏");
int age1=sharedperferences.getInt("age", 0);
String str="用户名为:"+username1+" 年龄为:"+age1;
Toast.makeText(getBaseContext(),str, 1).show();
break;
}
}
}
}