【android基础】android preferences

Preferences是一种应用程序内部轻量级的数据存储方案。

通过Context对象的getSharedPreferences方法获得的对象可以被同一应用程序下其他组件共享,而使用Activity对象的getPreferences方法获得的对象只能被调用该方法所在的Activity使用。

activity_preferences.xml

<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" >

    <EditText
        android:id="@+id/edit"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:inputType="textNoSuggestions"/>

</RelativeLayout>

PreferencesActivity.java

package com.example.android.sample4;

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


public class PreferencesActivity extends Activity {
	EditText editText;
	SharedPreferences sp;
	public final String EDIT_TEXT_KEY="EDIT_TEXT";

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_preferences);
        editText = (EditText)this.findViewById(R.id.edit);
        sp = getPreferences(MODE_PRIVATE);
        setPreferences();
        String result = sp.getString(EDIT_TEXT_KEY, null);
        if(result != null)
        {
        	editText.setText(result);
        }
             
    }

    public void setPreferences()
    {
    	SharedPreferences.Editor editor = sp.edit();
    	editor.putString(EDIT_TEXT_KEY, "test preferences");
    	editor.commit();
    }
    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.activity_preferences, menu);
        return true;
    }

    
}



  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值