android_preference

package com.example.myfirstapp;



import android.annotation.SuppressLint;

import android.app.Activity;

import android.content.Context;

import android.content.SharedPreferences;

import android.os.Bundle;

import android.view.View;

import android.widget.EditText;

import android.widget.Toast;



@SuppressLint("CommitPrefEdits")

public class SharedPreferenceActivity extends Activity {

    private static final String defaultIpaddress="192.168.1.1";

    private static final String defaultPort="9902";

    @Override

    protected void onCreate(Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);

        setContentView(R.layout.activity_preference);

    }

    

    /**

     * 设置

     * @param view

     * @throws Exception

     */

    public void saveBtnClicked(View view)throws Exception{

        String ip=((EditText)findViewById(R.id.ip)).getText().toString();

        String port=((EditText)findViewById(R.id.port)).getText().toString();

        //getPreferences(mode) 只使用一个参数设置文件

        SharedPreferences.Editor editor=getSharedPreferences("preference", Context.MODE_PRIVATE).edit();

        editor.putString("ip",ip);

        editor.putString("port", port);

        editor.commit();

        Toast.makeText(view.getContext(),R.string.file_operator_success,Toast.LENGTH_SHORT).show();

    }

    

    /**

     * 恢复默认

     * @param view

     * @throws Exception

     */

    public void backBtnClicked(View view)throws Exception{

        SharedPreferences settings=getSharedPreferences("default", Context.MODE_PRIVATE);

        SharedPreferences.Editor editor=settings.edit();

        editor.putString("ip", defaultIpaddress);

        editor.putString("port", defaultPort);

        editor.commit();

        

        String ip=settings.getString("ip", "");

        String port=settings.getString("port", "");

        

        SharedPreferences customSettings=getSharedPreferences("preference", Context.MODE_PRIVATE);

        SharedPreferences.Editor customEditor=customSettings.edit();        

        customEditor.putString("ip",ip);

        customEditor.putString("port", port);

        customEditor.commit();

        

        ((EditText)findViewById(R.id.ip)).setText(customSettings.getString("ip", ""));

        ((EditText)findViewById(R.id.port)).setText(customSettings.getString("port", ""));

    }

}

你可能感兴趣的:(Preference)