컴퓨터공부/Android

savedInstanceState 사용법 + fragment 예제

achivenKakao 2018. 4. 5. 00:12

화면이 회전되거나 크기가 변할 때 화면이 다시 그려지는데,

View 안의 데이터가 유지가 되지 않습니다.


이럴 때, savedInstanceState를 사용하면 View 안의 데이터를 보존 할 수 있습니다.


class내에서 public void onSaveInstanceState(Bundle outState) 함수를 재정의하여 사용하면 됩니다.



MainActivity.java

public class MainActivity extends AppCompatActivity {

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.savefragment);
}

public static class CounterFragment extends Fragment{
@Nullable
@Override
public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {

View root = inflater.inflate(R.layout.counterfragment, container, false);
Button btnIncrease = root.findViewById(R.id.btnincrease);
final TextView textCounter = root.findViewById(R.id.textcounter);
if(savedInstanceState != null){
textCounter.setText(Integer.toString((savedInstanceState.getInt("counter"))));
}


btnIncrease.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
int count = Integer.parseInt(textCounter.getText().toString());
textCounter.setText(Integer.toString(count+1));
}
});


return root;
}

@Override
public void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);

TextView textCounter = getView().findViewById(R.id.textcounter);
int counter = Integer.parseInt(textCounter.getText().toString());
outState.putInt("counter", counter);
}
}

} 



savefragment.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
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:id="@+id/counterfragment"
android:name="com.study.practice.saveinstancestate.MainActivity$CounterFragment"
android:layout_width="match_parent"
android:layout_height="wrap_content" />

</LinearLayout> 



counterfragment.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#ffff00"
android:gravity="center_horizontal"
android:orientation="vertical">

<TextView
android:id="@+id/textcounter"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="0"
android:textColor="#ff0000"
android:textSize="40sp" />

<Button
android:id="@+id/btnincrease"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="increase" />

</LinearLayout>