4

I have created my layout with ConstraintLayout and as ConstraintLayout allows you to build complex layouts without having to nest View. In my case, I want multiple view click events.

I have tried using Group as you can get a list of ids that are members of your Group in your code and set click listener.

 fun Group.setAllOnClickListener(listener: View.OnClickListener?) {
            referencedIds.forEach { id ->
                rootView.findViewById<View>(id).setOnClickListener(listener)
            }
        }

However, this does not seem to work as of the ConstraintLayout version 2.0.0-beta2. This code is working till 2.0.0-alpha3. I have implemented using multiple ConstraintLayout so is it alright to use nested constraint layout?

I am using MotionLayout and other animation of constraint layout so I can't use a lower version of ConstraintLayout.

4

1 回答 1

2

组的引用 ID 何时可用发生了变化。在2.0.0-beta2之前,它们可以立即在onCreate(). 似乎使用2.0.0-beta2,它们仅在布局后可用。我不确定这是否已记录在案,或者这只是一种副作用。

以下内容适用于2.0.0-beta2

class MainActivity : AppCompatActivity() {
    fun Group.setAllOnClickListener(listener: View.OnClickListener?) {
        referencedIds.forEach { id ->
            rootView.findViewById<View>(id).setOnClickListener(listener)
        }
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

        // Referenced ids are not available here but become available post-layout.
        layout.post {
            group.setAllOnClickListener(object : View.OnClickListener {
                override fun onClick(v: View) {
                    val text = (v as Button).text
                    Toast.makeText(this@MainActivity, text, Toast.LENGTH_SHORT).show()
                }
            })
        }
    }
}
于 2019-07-18T11:57:09.817 回答