iOS를 사랑하는 AOS 개발자

[Android] 안드로이드 AlertDialog 2탄 ( +RadioButton ) 본문

Android ( JAVA )/개발

[Android] 안드로이드 AlertDialog 2탄 ( +RadioButton )

아사안개 2021. 12. 31. 22:32
반응형
SMALL

👼🏻 초보 안드로이드 개발자가 매번 구글링하기 싫어서 정리하는 블로그 👼🏻 

 

안녕하세요!!

 

2021.12.31 - [Android/개발] - [Android] 안드로이드 AlertDialog

 

[Android] 안드로이드 AlertDialog

👼🏻 초보 안드로이드 개발자가 매번 구글링하기 싫어서 정리하는 블로그 👼🏻 안녕하세요! 2021.12.30 - [Android/개발] - [Android] 안드로이드 GridView 2탄 (feat.Adapter, AlertDialog) [Android] 안드로이..

devziner.tistory.com

저번엔 기본 AlertDialog 를 사용했다면,

이번엔 RadioButton 이 있는 AlertDialog 를 만들어 볼거에요!!!

( RadioButton 을 모른다면 ⏬  하단 링크 참고 😉 )

2021.12.21 - [Android/개발] - [Android] RadioButton 간단 사용법(feat. strings.xml)

 

[Android] RadioButton 간단 사용법(feat. strings.xml)

👼🏻 초보 안드로이드 개발자가 매번 구글링하기 싫어서 정리하는 블로그 👼🏻 [Android] CheckBox 간단 사용법 👼🏻 초보 안드로이드 개발자가 매번 구글링하기 싫어서 정리하는 블로그 👼

devziner.tistory.com

 

 

뷰 그리기 전에 구현 영상부터!

 

 

 

보시면 이제 슬슬 기초적인것들을 여기저기서 응용해서 쓰는 걸 확인 할 수 있어요!!

어떻게 응용했는지 한번 코드 보러가봅시다!

 

뷰부터 갑니다!

반응형
activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
    android:orientation="vertical"
    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"
    android:padding="20dp">

    <TextView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="안녕하세요! \n제품을 선택해주세요!"
        android:textAlignment="center"
        android:textSize="20dp"
        />

    <Button
        android:id="@+id/btn_alert"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="선택하러가기"
        android:layout_gravity="center"
        />
    <LinearLayout
        android:id="@+id/ll_layout"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="vertical"
        >
        <TextView
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:text="선택한 제품은"
            android:textAlignment="center"
            android:textSize="20dp"
            android:paddingTop="40dp"
            />
        <TextView
            android:id="@+id/tv_product"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:text="무엇"
            android:textAlignment="center"
            android:textSize="20dp"
            android:textColor="#F44336"
            />
        <TextView
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:text="입니다"
            android:textAlignment="center"
            android:textSize="20dp"
            />
        <ImageView
            android:id="@+id/iv_product_image"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:src="@drawable/iphone"
            />
    </LinearLayout>
</LinearLayout>

 

오늘도 역시나 뷰에 진심인 편......ㅎ

 

뷰에서 볼때

" 어랏? 왜 RadioGroup, RadioButton 이 없지??? "

라고 생각하셧을텐데

 

고건 바로

values 에 string-array 로 선언해놨기 때문이에요!

SMALL
data_array.xml
<?xml version="1.0" encoding="utf-8"?>
<resources>
    <string-array name="product">
        <item>아이폰</item>
        <item>맥북</item>
        <item>애플워치</item>
    </string-array>
</resources>

 

" 아니뭐야... 그래도 RadioGroup, RadioButton 가 없잖아.. 도대체 어디서 하는거야..??? "

라고 생각이 들텐데 이건 MainActivity 에서 설정해줄꺼에요!

( 안궁금하셨다면 뭐.. 어쩔수없고.. 😭 )

 

MainActivity
import android.content.DialogInterface;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import java.util.ArrayList;

public class MainActivity extends AppCompatActivity {

    // 전역변수
    Button btn_alert;
    TextView tv_product;
    LinearLayout ll_layout;
    ImageView iv_product_image;

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

        // xml 연결
        btn_alert = findViewById(R.id.btn_alert);
        tv_product = findViewById(R.id.tv_product);
        ll_layout = findViewById(R.id.ll_layout);
        iv_product_image = findViewById(R.id.iv_product_image);


        // 안보이게 숨기기
        ll_layout.setVisibility(View.INVISIBLE);

        // 나와라 alert!!
        btn_alert.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                String[] items = getResources().getStringArray(R.array.product); // values 에 작성한 string-array 불러오기
                int[] images = { R.drawable.iphone, R.drawable.macbook, R.drawable.watch }; // 이미지 배열. 이미지는 return 값이 integer 인것 까먹지 않기!
                ArrayList<String> selectItem = new ArrayList<>(); // RadioButton 선택 한 값 담을 ArrayList ( TEXT )
                ArrayList<Integer> selectImage = new ArrayList<>(); // RadioButton 선택 한 값 담을 ArrayList ( IMAGE )

                selectItem.add(items[0]); // 초기 값
                selectImage.add(images[0]); // 초기 값

                // Alert 선언
                new AlertDialog.Builder(MainActivity.this)
                        .setTitle("원하는 제품을 선택하세요")
                        .setSingleChoiceItems(R.array.product, 0, new DialogInterface.OnClickListener() { 
                            // setSingleChoiceItems 가 RadioGroup, RadioButton 을 해준다.
                            @Override
                            public void onClick(DialogInterface dialogInterface, int i) {
                                selectItem.clear(); // 하나의 값만 저장 되도록 모든 값 지워준다.
                                selectImage.clear(); // 하나의 값만 저장 되도록 모든 값 지워준다.
                                selectItem.add(items[i]); // 선택한 값 저장.
                                selectImage.add(images[i]); // 선택한 값 저장.
                            }
                        })
                        .setPositiveButton("확인", new DialogInterface.OnClickListener() {
                            // 확인 버튼을 클릭 했을때 이벤트
                            @Override
                            public void onClick(DialogInterface dialogInterface, int i) {
                                ll_layout.setVisibility(View.VISIBLE); // onCreate 에서 숨겨놨던 얘들 보여주기
                                tv_product.setText(selectItem.get(0)); // 선택한 값 적용
                                iv_product_image.setImageResource(selectImage.get(0)); // 선택한 값 적용
                            }
                        })
                        .setNegativeButton("취소", null)
                        .show();
            }
        });

    }


}

 

이로써 코드도 끝이에요!!

 

AlertDialog 는 보통 이런 예제에서 많이 쓰이죠 ( 아님... 말고... 😭 )

 

이런식으로 응용해서 많은 곳에서 써보세요 !

 

그럼 전 이만! 봐주셔서 감사합니다!

반응형
LIST
Comments