[Android] IntelliJ #4 Radio, CheckBox, ContextMenu, ImageButton

RadioButton

  • 선택된 값 textView에 출력하기

activity_main.xml

  • RadioGroup내부에 RadioButton을 추가한다.
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout
        xmlns:android="http://schemas.android.com/apk/res/android"
        xmlns:tools="http://schemas.android.com/tools"
        xmlns:app="http://schemas.android.com/apk/res-auto"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        tools:context=".MainActivity">

    <RadioGroup
            android:id="@+id/radioGroup"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            app:layout_constraintStart_toStartOf="parent"
            app:layout_constraintEnd_toEndOf="parent"
            app:layout_constraintBottom_toBottomOf="parent"
            app:layout_constraintTop_toTopOf="parent">

        <RadioButton
                android:text="사과"
                android:checked="true"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:id="@+id/radio1"/>
        <RadioButton
                android:text="바나나"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:id="@+id/radio2"/>
        <RadioButton
                android:text="오렌지"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:id="@+id/radio3"/>
    </RadioGroup>

    <TextView
            android:text="TextView"
            android:layout_width="230dp"
            android:layout_height="43dp"
            android:id="@+id/textView"
            app:layout_constraintTop_toBottomOf="@+id/radioGroup"
            app:layout_constraintStart_toStartOf="parent"
            android:layout_marginTop="48dp"
            android:layout_marginStart="88dp"/>

</androidx.constraintlayout.widget.ConstraintLayout>

MainActivity

package com.example.sample11

import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.util.Log
import com.example.sample11.databinding.ActivityMainBinding

class MainActivity : AppCompatActivity() {

    val binding by lazy { ActivityMainBinding.inflate(layoutInflater) }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(binding.root)

        binding.radioGroup.setOnCheckedChangeListener{ _, checkedId->
            Log.d("RadioButton", "radio 버튼 클릭")
            when(checkedId) {
                R.id.radio1 -> binding.textView.text = "사과가 선택되었습니다"
                R.id.radio2 -> binding.textView.text = "바나나가 선택되었습니다"
                R.id.radio3 -> binding.textView.text = "오렌지가 선택되었습니다"
            }
        }
    }
}
  • binding사용하려면 app > build.gradle에 추가하기
    buildFeatures{
        viewBinding true
    }

CheckBox

  • checkBox의 체크 여부 표시

activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout
        xmlns:android="http://schemas.android.com/apk/res/android"
        xmlns:tools="http://schemas.android.com/tools"
        xmlns:app="http://schemas.android.com/apk/res-auto"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        tools:context=".MainActivity">

    <CheckBox
            android:text="CheckBox"
            android:layout_width="143dp"
            android:layout_height="83dp" android:id="@+id/checkBox"
            app:layout_constraintTop_toTopOf="parent"
            app:layout_constraintBottom_toTopOf="@+id/textView" app:layout_constraintEnd_toEndOf="parent"
            app:layout_constraintStart_toStartOf="parent" app:layout_constraintVertical_bias="0.867"
            app:layout_constraintHorizontal_bias="0.501"/>

    <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="Hello World!"
            app:layout_constraintBottom_toBottomOf="parent"
            app:layout_constraintLeft_toLeftOf="parent"
            app:layout_constraintRight_toRightOf="parent"
            app:layout_constraintTop_toTopOf="parent" android:id="@+id/textView"
            app:layout_constraintVertical_bias="0.569"/>

</androidx.constraintlayout.widget.ConstraintLayout>

MainActivity

#1

package com.example.sample12

import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.widget.CheckBox
import android.widget.TextView

class MainActivity : AppCompatActivity() {

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)

        setContentView(R.layout.activity_main)

        val checkBox = findViewById<CheckBox>(R.id.checkBox)
        val textView = findViewById<TextView>(R.id.textView)

        checkBox.setOnCheckedChangeListener{_, isChecked ->
            //isChecked를 이용해서 체크 여부를 판별한다.
            if(isChecked){
                textView.text = "체크됨"
            }else{
                textView.text = "안됨"
            }
        } 
    }
}

#2

  • checkbox가 여러개인 경우 when에 id를 추가해서 사용한다.
package com.example.sample12

import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.widget.CheckBox
import android.widget.CompoundButton
import android.widget.TextView
import com.example.sample12.databinding.ActivityMainBinding

class MainActivity : AppCompatActivity() {

    val binding by lazy { ActivityMainBinding.inflate(layoutInflater) }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)

        setContentView(binding.root)
        binding.checkBox.setOnCheckedChangeListener(checklistener)
    }

    val checklistener by lazy {
        CompoundButton.OnCheckedChangeListener{ buttonView, isChecked ->
            val textView = findViewById<TextView>(R.id.textView)
  
            if(isChecked){
                when(buttonView.id){
                    R.id.checkBox -> {
                        textView.text = "체크됨"
                    }
                }
            }else{
                when(buttonView.id){
                    R.id.checkBox -> {
                        textView.text = "안됨"
                    }
                }
            }
        }
    }
}
  • binding사용하려면 app > build.gradle에 추가하기
    buildFeatures{
        viewBinding true
    }

Context Menu

  • textView를 길게 쭉 누르면 context menu 활성화됨

res > menu > context_menu_main.xml 추가

<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android">
    <item
        android:id="@+id/text_color"
        android:title="글자색변경"/>

    <item
        android:id="@+id/text_back_color"
        android:title="배경색 변경"/>

    <item
        android:id="@+id/text_basic"
        android:title="초기화"/>

</menu>

activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout
        xmlns:android="http://schemas.android.com/apk/res/android"
        xmlns:tools="http://schemas.android.com/tools"
        xmlns:app="http://schemas.android.com/apk/res-auto"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        tools:context=".MainActivity">
    <TextView
            android:id="@+id/textview"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="ContextMenu 보기\n(길게 누르세요.)"
            android:textSize="30sp"
            app:layout_constraintBottom_toBottomOf="parent"
            app:layout_constraintLeft_toLeftOf="parent"
            app:layout_constraintRight_toRightOf="parent"
            app:layout_constraintTop_toTopOf="parent" tools:textAlignment="center"/>

</androidx.constraintlayout.widget.ConstraintLayout>

MainActivity

package com.example.sample13

import android.graphics.Color
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.view.ContextMenu
import android.view.MenuItem
import android.view.View
import android.widget.TextView
import com.example.sample13.databinding.ActivityMainBinding

class MainActivity : AppCompatActivity() {

    val binding by lazy{ ActivityMainBinding.inflate(layoutInflater)}

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(binding.root)

        //textView에 메뉴 세팅 -> 길게 누르면 나옴
        registerForContextMenu(binding.textview)
    }

    //메뉴 불러오는 부분
    override fun onCreateContextMenu(menu: ContextMenu?, v: View?, menuInfo: ContextMenu.ContextMenuInfo?) {
        menuInflater.inflate(R.menu.context_menu_main, menu)
    }

    override fun onContextItemSelected(item: MenuItem): Boolean {
        val textView = findViewById<TextView>(R.id.textview)
        when(item?.itemId){
            R.id.text_color ->{
                textView.setTextColor(Color.GREEN)
                textView.text = "글자색 변경"
            }
            R.id.text_back_color ->{
                textView.setBackgroundColor(Color.YELLOW)
                textView.text = "배경색 변경"
            }
            R.id.text_basic ->{
                textView.setTextColor(Color.WHITE)
                textView.setBackgroundColor(Color.BLACK)
                textView.text = "초기화"
            }
        }
        return super.onContextItemSelected(item)
    }
}
  • binding사용하려면 app > build.gradle에 추가하기
    buildFeatures{
        viewBinding true
    }

ImageButton

  • imageButton을 클릭하면 textView가 변경되고 alert를 띄운다.

res > drawable > image추가

  • 버튼으로 만들고 싶은 이미지를 추가한다.

activity_main.xml

  • ImageButton tag를 이용한다.
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout
        xmlns:android="http://schemas.android.com/apk/res/android"
        xmlns:tools="http://schemas.android.com/tools"
        xmlns:app="http://schemas.android.com/apk/res-auto"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        tools:context=".MainActivity">
    <TextView
            android:id="@+id/textView"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="Hello World!"
            android:textSize="30sp"
            app:layout_constraintBottom_toBottomOf="parent"
            app:layout_constraintLeft_toLeftOf="parent"
            app:layout_constraintRight_toRightOf="parent"
            app:layout_constraintTop_toTopOf="parent"
            app:layout_constraintVertical_bias="0.264"/>

    <ImageButton
            android:layout_width="432dp"
            android:layout_height="175dp"
            app:srcCompat="@drawable/kotlin"
            android:id="@+id/imageButton"
            app:layout_constraintStart_toStartOf="parent"
            app:layout_constraintEnd_toEndOf="parent"
            app:layout_constraintBottom_toBottomOf="parent"
            app:layout_constraintTop_toTopOf="parent"/>

</androidx.constraintlayout.widget.ConstraintLayout>

✅ MainActivity

package com.example.sample27

import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.view.View
import android.widget.ImageButton
import android.widget.TextView
import androidx.appcompat.app.AlertDialog

class MainActivity : AppCompatActivity(), View.OnClickListener {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

        val imgBtn = findViewById<ImageButton>(R.id.imageButton)

        //activity_main.xml에 onclick없어도 됨
        imgBtn.setOnClickListener(this)
    }

    override fun onClick(v: View?) {
        val tv = findViewById<TextView>(R.id.textView)

        if(v != null){
            when(v.id){
                R.id.imageButton->{
                    val builder = AlertDialog.Builder(this)
                    builder.setTitle("제목")
                    builder.setMessage("imgBtn click!")
                    builder.show()

                    tv.text = "imgBtn click!"
                }
            }
        }
    }
}

좋은 웹페이지 즐겨찾기