android应用开发详解(十九)----------------------preference

android中数据存取的方式:Preference(配置)、File(文件)、SQLite数据和网络。
android中提供Content Provider组件实现应用程序组件之间数据的共享。
file explorer中查看文件信息

1、工程目录


2、MainActivity.java

package com.example.test_prefernce;

import android.os.Bundle;
import android.app.Activity;
import android.content.SharedPreferences;
import android.view.Menu;
import android.widget.Button;
import android.widget.EditText;

public class MainActivity extends Activity {
	@Override
	protected void onStop() {
		// TODO Auto-generated method stub
		super.onStop();
		// 获得编辑器
		SharedPreferences.Editor editor = getSharedPreferences(TEMP_SMS,
				MODE_WORLD_WRITEABLE).edit();
		// 将EditText中的内容添加到编辑器
		editor.putString("sms_content", myEdit.getText().toString());
		// 提交编辑器内容
		editor.commit();
	}

	// 实例化EditText和Button
	private EditText myEdit;
	private Button myBtn;
	private static final String TEMP_SMS = "temp_sms";

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.main);
		myEdit = (EditText) findViewById(R.id.edit01);
		myBtn = (Button) findViewById(R.id.button);
		// 获得sharedPreferences实例
		SharedPreferences pre = getSharedPreferences(TEMP_SMS,
				MODE_WORLD_READABLE);
		// 从sharedPreferens中获得短信内容
		String content = pre.getString("sms_content", "");
		// 在EditText中显示内容
		myEdit.setText(content);
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// Inflate the menu; this adds items to the action bar if it is present.
		getMenuInflater().inflate(R.menu.main, menu);
		return true;
	}

}

3、布局文件

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="vertical" >

    <EditText 
        android:id="@+id/edit01"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:lines="4"
        android:text=""/>
    <Button 
        android:id="@+id/button"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="发送"/>

</LinearLayout>


猜你喜欢

转载自blog.csdn.net/hulan_baby/article/details/40153137