![](/img/trans.png)
[英]How can I make a linearLayout (with other views and content within) to be clickable in android studio xml and using Kotlin in the backend?
[英]Android Studio: How to affect multiple Views at the same time? (XML + Kotlin)
我試圖做到這一點,當我將鼠標懸停在我的 30 個左右的 ImageView 之一上時,灰色背景出現在它們后面。 不幸的是,除了單獨調用每個 ImageView 之外,我不知道該怎么做。 (我在 Kotlin 中編寫代碼,在 Android Studio 中使用我相鄰的 xml 文件中的 id 調用。)例如,而不是說:
if (binding.appleImg || binding.pizzaImg || binding.fishImg ....) {do stuff}
我怎么能說這樣的話:
if (groupOfFoodImages ...) {do stuff}
首先,您需要以編程方式了解布局中的哪些元素,以便使用以下功能:
fun View.getAllChildren(): List<View> {
val result = ArrayList<View>()
if (this !is ViewGroup) {
result.add(this)
} else {
for (index in 0 until this.childCount) {
val child = this.getChildAt(index)
result.addAll(child.getAllChildren())
}
}
return result
}
然后循環查找所有imageView
並設置它們的背景。 我猜你正在使用片段,然后像下面這樣稱呼它:
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
for(myView in view.getAllChildren()) {
if (myView.javaClass.name.contains("ImageView")) {
myView.background = resources.getDrawable(R.drawable.your_background_image)
}
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.