我试图做到这一点,以便当我将鼠标悬停在 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)
}
}
}
您不能,因为您无法将特定的单个对象操作(您悬停在其上的一个 imageView)分配给一组对象。您可以在不迭代整个列表的情况下执行以下操作:a) 覆盖
onFocusChanged
并更改 hasFocus
的背景。当焦点再次更改时,您可以设置回旧背景并将灰色背景放置到新焦点,或者像在 Kotlin 中一样 b) 使用可组合项和 cooroutineScopes 来了解当前显示哪个对象正在相应地更改背景。我做了类似的事情,在对象可见时播放视频,在我的例子中是使用 LazyRow 构建的自动滑块
val listState = rememberLazyListState()
var currentMediaIndex by remember { mutableStateOf(0) }
LaunchedEffect(currentMediaIndex) {
while (true) {
delay(MainActivity.mediaDelay)
if (thisPlayer != null && !thisPlayer!!.isPlaying && medias.isNotEmpty()) {
val nextIndex = (currentMediaIndex + 1) % medias.size
currentMediaIndex = nextIndex
coroutineScope.launch {
listState.animateScrollToItem(currentMediaIndex)
when (listState.isScrollInProgress) {
false -> {
if (vList.contains(currentMediaIndex))
thisPlayer!!.play()
}
else -> {}
}
}
}
}
}