note

Android Preferences 읽고 쓰기(환경설정) 본문

Android/기본

Android Preferences 읽고 쓰기(환경설정)

투한 2012. 2. 1. 21:10



main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    >
	<EditText  
	    android:id="@+id/edit"
	    android:layout_width="fill_parent" 
	    android:layout_height="wrap_content" 
	    />
	<Button  
	    android:id="@+id/write"
	    android:layout_width="fill_parent" 
	    android:layout_height="wrap_content" 
	    android:text="프리퍼런스 쓰기"
	    />
	<Button  
	    android:id="@+id/read"
	    android:layout_width="fill_parent" 
	    android:layout_height="wrap_content" 
	    android:text="프리퍼런스 읽기"
	    />
	<TextView  
	    android:id="@+id/view"
	    android:layout_width="fill_parent" 
	    android:layout_height="wrap_content"
	    />
</LinearLayout>



Main Activity
package net.npaka.preferencesex;

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

public class PreferencesEx extends Activity implements View.OnClickListener{
	private EditText editText;//텍스트 박스
	private Button btnWrite;//읽기 버튼
	private Button btnRead;//쓰기 버튼
	private TextView view;
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.main);

		editText = (EditText)findViewById(R.id.edit);
		btnWrite = (Button)findViewById(R.id.write);
		btnRead= (Button)findViewById(R.id.read);
		view= (TextView)findViewById(R.id.view);

		btnWrite.setOnClickListener(this);
		btnRead.setOnClickListener(this);
	}

	public void onClick(View v) {
		if(v==btnWrite){
			//SharedPreferences 객체 구하기(1)
			SharedPreferences pref = getSharedPreferences("PreferencesEx",MODE_PRIVATE);

			//프리퍼런스의 쓰기(2)
			SharedPreferences.Editor editor =pref.edit();
			editor.putString("text", editText.getText().toString());
			//반드시 commit()메소드를 호출해야 저장됨
			editor.commit();
			editText.setText("");
		}else if(v==btnRead){
			//SharedPreferences 객체 구하기(1)
			SharedPreferences pref = getSharedPreferences("PreferencesEx",MODE_PRIVATE);

			//프리퍼런스로부터 읽기(3)
			view.setText(pref.getString("text",""));
		}
	}
}


'Android > 기본' 카테고리의 다른 글

Android Animaiton 으로 효과  (3) 2012.02.01
Android Paint로 그림그리기  (0) 2012.02.01
안드로이드 환경설정Preferences , 메뉴  (0) 2012.01.31
RSS 가져오기(뉴스)  (1) 2012.01.31
Progressbar로 로딩표현 (인터넷로딩)  (0) 2012.01.31