본문 바로가기
App/Android Studio

Android Studio - 공유 프레퍼런스, dialog

by 코젼 2022. 8. 11.
728x90
반응형

2022-08-11(39일차)



📃Dialog 예제

 


📝activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout 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"
    tools:context=".MainActivity">

    <TextView
        android:id="@+id/tv"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Hello World!"
        android:textSize="40dp"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

</androidx.constraintlayout.widget.ConstraintLayout>

📝MainActivity.java

package com.project.test05;

import androidx.appcompat.app.AppCompatActivity;

import android.app.AlertDialog;
import android.content.DialogInterface;
import android.os.Bundle;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;

public class MainActivity extends AppCompatActivity {
    TextView tv;

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

        tv = findViewById(R.id.tv);
        tv.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                onDialog();
            }
        });


    }

    public void onDialog() {
        AlertDialog.Builder dialog = new AlertDialog.Builder(this);
        dialog.setTitle("이름입력");
        dialog.setMessage("사용자의 이름을 입력합니다");

        //다이얼로그에 에디트텍스트를 추가한다
        EditText et_name = new EditText(this);
        dialog.setView(et_name);

        dialog.setPositiveButton("OK", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialogInterface, int i) {
                tv.setText(et_name.getText().toString());
            }
        });

        dialog.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialogInterface, int i) {
            }
        });

        dialog.show();
    }
}

📃공유 프레퍼런스 xml생성 예제


 


📝activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<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"
    tools:context=".MainActivity"
    android:orientation="vertical">

    <TextView
        android:id="@+id/textView"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Hello World!" />

    <CheckBox
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:id="@+id/cb_sound"
        android:text="sound"/>

</LinearLayout>


📝MainActivity.java

package com.project.test06;

import androidx.appcompat.app.AppCompatActivity;

import android.content.SharedPreferences;
import android.os.Bundle;
import android.util.Log;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.RadioGroup;

public class MainActivity extends AppCompatActivity {

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

        CheckBox cb = findViewById(R.id.cb_sound);
        cb.setOnCheckedChangeListener(checkedChangeListener);
    }

    CompoundButton.OnCheckedChangeListener checkedChangeListener = new CompoundButton.OnCheckedChangeListener() {
        @Override
        public void onCheckedChanged(CompoundButton compoundButton, boolean bChecked) {
            Log.i("jyeon", "check 상태 변경 : " + bChecked);

            // 공유 프레퍼런스에 저장
            SharedPreferences pref = getSharedPreferences("sharedpreferences", MODE_PRIVATE);
            SharedPreferences.Editor editor = pref.edit();
            editor.putBoolean("sound", bChecked);
            editor.commit();
        }
    };

    @Override
    protected void onResume() {
        super.onResume();
        SharedPreferences pref = getSharedPreferences("sharedpreferences", MODE_PRIVATE);
        boolean bSound = pref.getBoolean("sound", false);

        CheckBox cb = findViewById(R.id.cb_sound);
        cb.setChecked(bSound);
    }

    @Override
    protected void onPause() {
        super.onPause();
    }
}

📝sharedpreferences.xml

<?xml version='1.0' encoding='utf-8' standalone='yes' ?>
<map>
    <boolean name="sound" value="true" />
</map>

📃사용자 이름 저장하기 ... 미완성 코드 (공유 프레퍼런스 미적용)

◾ 공유 프레퍼런스에 저장하게 되면, 애플리케이션을 종료하고 다시 키더라도 정보가 동일하게 남아있는다.

 ex) TextView의 값을 dialog를 통해 바꾸었을 때, 애플리케이션을 종료하더라도 바꾼 데이터로 저장되어있다.


user_name이 저장된다.


📝activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout 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:layout_margin="10dp"
    tools:context=".MainActivity">

    <TextView
        android:id="@+id/tv"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="사용자"
        android:textAppearance="?android:voiceLanguage"
        android:textSize="30dp" />

    <TextView
        android:id="@+id/tv_name"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_toRightOf="@+id/tv"
        android:textAppearance="?android:voiceLanguage"
        android:textSize="20dp" />

    <Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignBaseline="@+id/tv_name"
        android:layout_alignParentRight="true"
        android:onClick="onClickInput"
        android:text="사용자입력"
        android:textSize="20dp" />

</RelativeLayout>


📝MainActivity.java

package com.project.test07;

import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;

import android.content.DialogInterface;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;

public class MainActivity extends AppCompatActivity {
    TextView tv_name;

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

        tv_name = findViewById(R.id.tv_name);
        readUserName();
    }

    void readUserName() {
        SharedPreferences pref = getPreferences(MODE_PRIVATE);
        String str_name = pref.getString("user_name", "unknown");
        tv_name.setText(str_name);
    }

    void writeName(String name) {
        SharedPreferences pref = getPreferences(MODE_PRIVATE);
        SharedPreferences.Editor editor = pref.edit();
        editor.putString("user_name", name);
        editor.commit();
    }

    public void onClickInput(View view) {
        AlertDialog.Builder dialog = new AlertDialog.Builder(this);
        dialog.setTitle("이름입력");
        dialog.setMessage("사용자의 이름을 입력합니다");

        //다이얼로그에 에디트텍스트를 추가한다
        EditText et_name = new EditText(this);
        dialog.setView(et_name);

        dialog.setPositiveButton("OK", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialogInterface, int i) {
                String str = et_name.getText().toString();
                writeName(str);
                readUserName();
            }
        });

        dialog.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialogInterface, int i) {
                writeName("unknown");
                readUserName();
            }
        });
        dialog.show();
    }
}

📝MainActivity.xml

<?xml version='1.0' encoding='utf-8' standalone='yes' ?>
<map>
    <string name="user_name">kjy</string>
</map>

 

728x90
반응형

댓글