- 회전하면 reset되는 데이터 유지하는 방법
<MainActivity.java>
package com.example.cycleex;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
public class MainActivity extends AppCompatActivity {
public static final String PLAY_LEVEL = "playLevel";
public static final String PLAY_SCORE = "playScore";
TextView textLevel, textScore;
Button btnLevelup, btnScoreup;
int mLevel=0 , mScore=0;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
textLevel = findViewById(R.id.textLevel);
textScore = findViewById(R.id.textScore);
btnLevelup = findViewById(R.id.btnLevelup);
btnLevelup.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
mLevel++;
textLevel.setText("레벨: "+mLevel );
}
});
btnScoreup = findViewById(R.id.btnScoreup);
btnScoreup.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
mScore +=100;
textScore.setText("점수 : " +mScore);
}
});
if(savedInstanceState == null){
}
else{
mLevel = savedInstanceState.getInt(PLAY_LEVEL);
mScore = savedInstanceState.getInt(PLAY_SCORE);
textLevel.setText("레벨: "+ mLevel);
textScore.setText("점수: "+ mScore);
}
}
@Override
protected void onSaveInstanceState(@NonNull Bundle outState) {
outState.putInt(PLAY_LEVEL, mLevel);
outState.putInt(PLAY_SCORE, mScore);
super.onSaveInstanceState(outState);
}
}
<activity_main.xml>
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".MainActivity" >
<TextView
android:id="@+id/textLevel"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:textSize="15dp"
android:text="레벨 : 0" />
<Button
android:id="@+id/btnLevelup"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="레벨업" />
<TextView
android:id="@+id/textScore"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:textSize="15dp"
android:text="점수 : 0" />
<Button
android:id="@+id/btnScoreup"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="점수증가" />
</LinearLayout>
'Android' 카테고리의 다른 글
라즈베리 파이 연동) led on/off (0) | 2020.11.05 |
---|---|
안드로이드- 회전시 데이터 유지하기 (0) | 2020.11.05 |
안드로이드- 글 적고 저장 누르면 다시 실행시켰을 때 저장됨 (0) | 2020.11.05 |
안드로이드 - 이메일 저장 (0) | 2020.11.05 |
project - 오토믹 자동차 (0) | 2020.11.04 |