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

本文介绍如何在Android应用中使用Preference组件来存储和读取数据,包括创建SharedPreferences实例、编辑器操作、提交操作以及从SharedPreferences中获取数据的流程。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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>


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值