Я написал следующую функцию, и, похоже, она работает. Вы можете попробовать и сообщить мне, если обнаружите какие-либо проблемы.
private fun View.isOverlap(other: View, deltaX: Int = 0, deltaY: Int = 0): Boolean
{
val rectThis = Rect()
this.getHitRect(rectThis)
rectThis.offset(deltaX, deltaY) //addind delta to every side of Rect
val rectOther = Rect()
other.getHitRect(rectOther)
return rectThis.intersect(rectOther)
}
Main Activity XML
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:id="@+id/conLay"
android:layout_height="match_parent"
tools:context=".MainActivity">
<Button
android:id="@+id/v1"
android:layout_width="149dp"
android:layout_height="114dp"
android:layout_marginStart="164dp"
android:layout_marginTop="64dp"
android:text="v1"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
<Button
android:id="@+id/v2"
android:layout_width="126dp"
android:layout_height="114dp"
android:layout_marginTop="160dp"
android:layout_marginEnd="232dp"
android:text="v2"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintTop_toTopOf="parent" />
</androidx.constraintlayout.widget.ConstraintLayout>
MainActivity.kt
import android.graphics.Rect
import android.os.Bundle
import android.util.Log
import android.view.View
import android.widget.Button
import androidx.appcompat.app.AppCompatActivity
class MainActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
val v1 = findViewById<Button>(R.id.v1)
val v2 = findViewById<Button>(R.id.v2)
v1.setOnClickListener {
Log.d("One - two", v1.isOverlap(v2, 2, 1).toString())
Log.d("Two - one", v2.isOverlap(v1, 1, 2).toString())
}
}
}
private fun View.isOverlap(other: View, deltaX: Int = 0, deltaY: Int = 0): Boolean {
val rectThis = Rect()
this.getHitRect(rectThis)
Log.d("rectThis before change", rectThis.toShortString())
rectThis.offset(deltaX, deltaY)
Log.d("rectThis after change", rectThis.toShortString())
val rectOther = Rect()
other.getHitRect(rectOther)
Log.d("rectOther", rectOther.toShortString())
return rectThis.intersect(rectOther)
}