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.

View Bindingについて

Last updated at Posted at 2022-09-05

対象読者

  • ウィジェット特定で冗長なコード(findViewById)を書きたくない人

できるようになること

  • findViewByIdによる冗長なウィジェット特定を卒業できる

手順

  1. build.gradleを以下のように編集する
    android {
        compileSdk 32
    
        // ここから
        buildFeatures {
            viewBinding true
        }
        // ここまでを追記する
    
        省略・・・
    }
    
  2. アクティビティファイルを開く
    class MainActivity : AppCompatActivity() {
        // 追加ポイント1
        private lateinit var binding: ActivityMainBinding
    
        override fun onCreate(savedInstanceState: Bundle?) {
            super.onCreate(savedInstanceState)
            // 追加ポイント2
            binding = ActivityMainBinding.inflate(layoutInflater)
            setContentView(binding.root)
        }
    
  3. findViewByIdを利用せずにアクセスする方法
  • Before
    class MainActivity : AppCompatActivity() {
        private lateinit var binding: ActivityMainBinding
    
        override fun onCreate(savedInstanceState: Bundle?) {
            super.onCreate(savedInstanceState)
            binding = ActivityMainBinding.inflate(layoutInflater)
            setContentView(binding.root)
            val btnCurrent = findViewById<Button>(R.id.btnCurrent)
            btnCurrent.setOnClickListener {
                val txtResult = findViewById<TextView>(R.id.txtResult)
                txtResult.text = Date().toString()
            }
        }
    
  • After
    class MainActivity : AppCompatActivity() {
        private lateinit var binding: ActivityMainBinding
    
        override fun onCreate(savedInstanceState: Bundle?) {
            super.onCreate(savedInstanceState)
            binding = ActivityMainBinding.inflate(layoutInflater)
            setContentView(binding.root)
            binding.btnCurrent.setOnClickListener {
                binding.txtResult.text = Date().toString()
            }
        }
    

まとめ

  • view Bindingを使うとfindViewByIdを卒業できる
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?