0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

[Kotlin]enumの記述例(インテントでenumを受け渡す)

Last updated at Posted at 2021-08-24

概要

enumを使うとコードが読みやすくなりミスを減らすことにつながります。

今回は、enumで定義されたデータを2つのActivity間で受け渡すサンプルコードを共有したいと思います。

データを渡すActivity


class MainActivity : AppCompatActivity() {
    public enum class MyHandEnum{
        GU,
        CHOKI,
        PA
    }

    private lateinit var binding: ActivityMainBinding
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        binding = ActivityMainBinding.inflate(layoutInflater)
        setContentView(binding.root)

        binding.gu.setOnClickListener{
            openActivity(MyHandEnum.GU)
        }
        binding.choki.setOnClickListener{
            openActivity(MyHandEnum.CHOKI)
        }
        binding.pa.setOnClickListener{
            openActivity(MyHandEnum.PA)
        }
    }

    private fun openActivity(myHand: MyHandEnum){
        val intent = Intent(this,ResultActivity::class.java)
        intent.putExtra("MY_HAND",myHand)
        startActivity(intent)
    }
}

データを受け取るActivity


class ResultActivity : AppCompatActivity() {
    private lateinit var binding: ActivityResultBinding
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        binding = ActivityResultBinding.inflate(layoutInflater)
        setContentView(binding.root)

        val myHand: MainActivity.MyHandEnum = intent.getSerializableExtra("MY_HAND") as MainActivity.MyHandEnum

        when(myHand) {
            MainActivity.MyHandEnum.GU -> binding.myHandImage.setImageResource(R.drawable.gu)
            MainActivity.MyHandEnum.CHOKI -> binding.myHandImage.setImageResource(R.drawable.choki)
            MainActivity.MyHandEnum.PA -> binding.myHandImage.setImageResource(R.drawable.pa)
        }
    }
}

補足

enumを分岐させるwhen()を記述したい時は
スクリーンショット (654).png
when(~){  まで入力した時点で「Alt+Enter」を押すとenumの項目を自動入力してくれます:ok_hand:

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?