프로그래밍/안드로이드

안드로이드 - 프래그먼트 상태 저장하기

가카리 2015. 9. 8. 18:40
반응형

 

프래그먼트에 관한 내용은 안드로이드-프래그먼트-사용-간단-예제 를 참고하자.

 

이번에는 스마트폰의 상태 변경이나 화면이 가로로 될 때 자신의 데이터 저장을 해보자

 

이번에도 다음과 같이 3개의 파일을 만들어야 됨을 잊지 말자.

 

 

counterfragment.xml 파일 기본적인 프래그먼트를 구성하는 UI 파일

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"

android:orientation="vertical"

android:layout_width="match_parent"

android:layout_height="match_parent"

android:gravity="center_horizontal"

android:background="#ffff00"

>

 

<TextView

android:id="@+id/txtcounter"

android:layout_width="wrap_content"

android:layout_height="wrap_content"

android:textColor="#ff0000"

android:textSize="40sp"

android:text="0"

/>

<Button

android:id="@+id/btnincrease"

android:layout_width="wrap_content"

android:layout_height="wrap_content"

android:text="Increase"

/>

 

</LinearLayout>

 

 

save_fragment_state.xml 프래그먼트를 실제 사용하는 부분

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

android:orientation="vertical"

>

 

<TextView

android:layout_width="match_parent"

android:layout_height="wrap_content"

android:text="프래그먼트의 상태를 저장합니다."/>

<fragment

android:name="com.example.savefragmentstate.SaveFragmentState$CounterFragment"

android:id="@+id/counterfragment"

    android:layout_width="match_parent"

    android:layout_height="wrap_content"

></fragment>

 

</LinearLayout>

 

 

SaveFragmentState.java

 

package com.example.savefragmentstate;

 

import android.app.Activity;

import android.app.Fragment;

import android.os.Bundle;

import android.view.LayoutInflater;

import android.view.View;

import android.view.ViewGroup;

import android.widget.Button;

import android.widget.TextView;

 

public class SaveFragmentState extends Activity {

 

    @Override

    protected void onCreate(Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);

        setContentView(R.layout.save_fragment_state);

    }

 

    public static class CounterFragment extends Fragment{

          

        

        @Override

        public View onCreateView(LayoutInflater inflater, ViewGroup container,

                Bundle savedInstanceState) {

            // TODO Auto-generated method stub

            //onCreateView 프래그먼트의 UI 처음 그릴때 호출한다.

            //그래서 여기서 XML 이용해서 프래그먼트 UI 구성해준다.

            //container 전개자를 사용하여 xml 가져온다

            View root = inflater.inflate(R.layout.counterfragment, container, false);

            

            Button btnIncrease = (Button)root.findViewById(R.id.btnincrease);

            final TextView textCounter = (TextView)root.findViewById(R.id.txtcounter);

          

            

            if(savedInstanceState != null){

                textCounter.setText(Integer.toString(savedInstanceState.getInt("counter")));

            }

            

            

            //간단한 버튼 클릭 리스너 달아줌

            btnIncrease.setOnClickListener(new Button.OnClickListener(){

 

                @Override

                public void onClick(View arg0) {

                    // TODO Auto-generated method stub

                    int count = Integer.parseInt(textCounter.getText().toString());

                    textCounter.setText(Integer.toString(count + 1));

                }

                

            });

            

            return root;

        

        }

        

        //장비의 설정 상태 변경, 화면 방향 변경시에 다음 메소드가 호출된다.

        public void onSaveInstanceState(Bundle outState){

            super.onSaveInstanceState(outState);

            

            TextView textCounter = (TextView)getView().findViewById(R.id.txtcounter);

            int a = Integer.parseInt(textCounter.getText().toString());

            outState.putInt("counter", a);//번들에 저장 키와 값으로...

        }

    

    }

 

}

 

 

실행 화면

먼저 처음 상태에서 몇 번의 버튼을 눌러준 다음에

아래와 같이 가로로 되도 값이 그대로 유지된다.

 

반응형