我想问一下滑动图像拼图。 下面是向左或向右滑动的代码。 但是我有问题。
if (i + 1 < imageviews.size) {
if (imageviews[i + 1]!!.drawable == null) {
mGridLayout.removeView(imageviews[i + 1])
mGridLayout.addView(imageviews[i + 1], i)
val temp = imageviews[i + 1]
imageviews[i + 1] = imageviews[i]
imageviews[i] = temp
}
}
if (i - 1 >= 0) {
if (imageviews[i - 1]!!.drawable == null) {
mGridLayout.removeView(imageviews[i - 1])
mGridLayout.addView(imageviews[i - 1], i)
val temp = imageviews[i - 1]
imageviews[i - 1] = imageviews[i]
imageviews[i] = temp
}
}
答案 0 :(得分:1)
我已经更新了setOnClickListener()
函数,它似乎可以正常工作,但是我还没有完全解决它:
private fun setOnClickListener() {
Log.i(TAG, "${imageviews.size} ")
for (i in 0 until imageviews.size step 1) {
imageviews[i]!!.setOnClickListener {
Log.i(TAG, "${imageviews.size} $i")
val top: Int? = if (i - GRID_NO >= 0) i - GRID_NO else null
val bottom: Int? = if (i + GRID_NO < imageviews.size) i + GRID_NO else null
val left: Int? = if (i % GRID_NO > 0) i - 1 else null
val right: Int? = if (i % GRID_NO < GRID_NO - 1) i + 1 else null
// Log.i(TAG, "Top: $top Bottom: $bottom Left: $left Right: $right")
if (top != null && imageviews[top]!!.drawable == null) {
imageviews[top]!!.setImageDrawable(imageviews[i]!!.drawable)
mGridLayout.removeViewAt(i)
mGridLayout.addView(imageviews[i], i)
imageviews[i]!!.setImageDrawable(null)
} else if (bottom != null && imageviews[bottom]!!.drawable == null) {
imageviews[bottom]!!.setImageDrawable(imageviews[i]!!.drawable)
mGridLayout.removeViewAt(i)
mGridLayout.addView(imageviews[i], i)
imageviews[i]!!.setImageDrawable(null)
} else if (left != null && imageviews[left]!!.drawable == null) {
imageviews[left]!!.setImageDrawable(imageviews[i]!!.drawable)
mGridLayout.removeViewAt(i)
mGridLayout.addView(imageviews[i], i)
imageviews[i]!!.setImageDrawable(null)
} else if (right != null && imageviews[right]!!.drawable == null) {
imageviews[right]!!.setImageDrawable(imageviews[i]!!.drawable)
mGridLayout.removeViewAt(i)
mGridLayout.addView(imageviews[i], i)
imageviews[i]!!.setImageDrawable(null)
}
if (isSolved()) {
Toast.makeText(this, "Success , true", Toast.LENGTH_SHORT).show()
}
}
}
}
已更新isSolved()请求后的功能
更新后的isSolved()
如下所示:
private fun isSolved(): Boolean {
var solved = true
for (i in 0 until GRID_NO) {
for (j in 0 until GRID_NO) {
val index: Int = i * GRID_NO + j
if (imageviews[index]!!.drawable == null) {
continue
} else if (imageviews[index]!!.drawable != imageViews[i][j]!!.drawable) {
solved = false
break
}
}
}
return solved
}
请注意,如果除空单元格以外的所有单元格都位于正确的位置,则此版本将返回true,这意味着空单元格可以是末尾的任何单元格。如果这些难题通常具有更受限制的成功规则,例如空单元格应该在拐角处,则需要对其进行更新。