본문 바로가기

개인공부

안드로이드 : Radio버튼 구현(setImageResource 구현)

반응형

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"
    android:gravity="center_horizontal"
    tools:context=".MainActivity"
    android:orientation="vertical">

    <CheckBox
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:id="@+id/check1"
        android:text="버튼활성화" />
    <EditText
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:textSize="20dp"
    android:hint="입력하세요"
    android:id="@+id/edit1"></EditText>
    <Button
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="버튼활성화됬으면Toast"
        android:gravity="center_horizontal"
        android:textSize="20dp"
        android:id="@+id/btn1"/>

    <RadioGroup
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:id="@+id/group1"
        android:layout_gravity="center_horizontal"
        android:orientation="horizontal"
        android:visibility="invisible">

        <RadioButton
            android:id="@+id/g1"
            android:text="강아지"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"/>
        <RadioButton
            android:id="@+id/g2"
            android:text="고양이"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"/>
        <RadioButton
            android:id="@+id/g3"
            android:text="슬기"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"/>
    </RadioGroup>
    <ImageView
        android:id="@+id/image1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"/>



</LinearLayout>

MainActivity

package com.example.myapplication;

import androidx.appcompat.app.AppCompatActivity;

import android.media.Image;
import android.os.Bundle;
import android.provider.MediaStore;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.TextView;
import android.widget.Toast;

public class MainActivity extends AppCompatActivity {
    String str;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        final Button but1 =(Button)findViewById(R.id.btn1);
        final EditText edit1 = (EditText) findViewById(R.id.edit1);
        final CheckBox check1 = (CheckBox) findViewById(R.id.check1);
        final ImageView image1 = (ImageView) findViewById(R.id.image1);
        final RadioGroup radio1 = (RadioGroup) findViewById(R.id.group1);
        final RadioButton g1 = (RadioButton) findViewById(R.id.g1);
        final RadioButton g2 = (RadioButton) findViewById(R.id.g2);
        final RadioButton g3 = (RadioButton) findViewById(R.id.g3);
        final InputMethodManager imm = (InputMethodManager) getSystemService(INPUT_METHOD_SERVICE);

        check1.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                but1.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {


                    str = edit1.getText().toString();
                    if(str.equals("")){
                        Toast.makeText(getApplicationContext(),"에러입니다.",Toast.LENGTH_LONG).show();

                    }else{
                        Toast.makeText(getApplicationContext(),str,Toast.LENGTH_LONG).show();
                    }

                    //Radio 초기화
                    radio1.setVisibility(View.VISIBLE);
                    radio1.clearCheck();

                    }
                });

            }
        });

        radio1.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(RadioGroup group, int checkedId) {
                imm.hideSoftInputFromWindow(radio1.getWindowToken(),0);
                int rb = radio1.getCheckedRadioButtonId();

                switch(rb){
                    case R.id.g1:
                        image1.setImageResource(R.mipmap.dog);
                        break;

                    case R.id.g2:
                        image1.setImageResource(R.mipmap.cat);
                        break;

                    case R.id.g3:
                        image1.setImageResource(R.mipmap.slggi);
                        break;
                    default:
                        Toast.makeText(getApplicationContext(),"버튼을 클릭해주세요",Toast.LENGTH_LONG).show();
                       break;

                }
            }
        });



    }
}

 

 

        radio1.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(RadioGroup group, int checkedId) {

radio버튼의 활성화가되고 onCheckedChanged check가 활성화되었을경우 실행하는 Method

 

                imm.hideSoftInputFromWindow(radio1.getWindowToken(),0);

radio 체크하는 함수실행시 키보드가 올라오는 현상을 지워주는 Method

 

                int rb = radio1.getCheckedRadioButtonId();

                switch(rb){
                    case R.id.g1:
                        image1.setImageResource(R.mipmap.dog);
                        break;

                    case R.id.g2:
                        image1.setImageResource(R.mipmap.cat);
                        break;

                    case R.id.g3:
                        image1.setImageResource(R.mipmap.slggi);
                        break;
                    default:
                        Toast.makeText(getApplicationContext(),"버튼을 클릭해주세요",Toast.LENGTH_LONG).show();
                       break;

                }

 

인티저형 rb에 getCheckedRadioButtonId라는 값을 넣어 현재 몇번째 radio를 선택했는지 값을 반환

그값을 case에 따라 R.id.g1 값과 rb값을 매칭시켜서 실행할 함수를 선택

 

중복되는 이미지가 많은경우 for문을 활용하거나 배열을 활용해서 짧은 소스로 구현가능하다.

 

반응형