我已经使用下面的代码添加RelativeLayout
了。RelativeLayout
var _root: ViewGroup? = null
private var _xDelta: Float = 0F
private var _yDelta: Float = 0F
lateinit var layoutParams: RelativeLayout.LayoutParams
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_add)
_root = findViewById(R.id.root)
_view = RelativeLayout(this)
_view?.setBackgroundColor(Color.BLUE)
layoutParams = RelativeLayout.LayoutParams(280, 280)
layoutParams.leftMargin = 0
layoutParams.topMargin = 0
layoutParams.bottomMargin = 0
layoutParams.rightMargin = 0
// Adding Rule
layoutParams.addRule(RelativeLayout.ALIGN_PARENT_BOTTOM)
layoutParams.addRule(RelativeLayout.ALIGN_PARENT_RIGHT)
_view?.layoutParams = layoutParams
_view?.setOnTouchListener(this)
_root?.addView(_view)
}
如果我触摸视图并移动手指,它将移动视图以跟随我的手指。下面是它的代码: -
override fun onTouch(view: View, event: MotionEvent): Boolean {
val X = event.rawX
val Y = event.rawY
when (event.action and MotionEvent.ACTION_MASK) {
MotionEvent.ACTION_DOWN -> {
val lParams = view.layoutParams as RelativeLayout.LayoutParams
_xDelta = X - lParams.leftMargin
_yDelta = Y - lParams.topMargin
}
MotionEvent.ACTION_UP -> {
}
MotionEvent.ACTION_POINTER_DOWN -> {
}
MotionEvent.ACTION_POINTER_UP -> {
}
MotionEvent.ACTION_MOVE -> {
// Removing the rule to apply the effects
layoutParams.removeRule(RelativeLayout.ALIGN_PARENT_BOTTOM)
layoutParams.removeRule(RelativeLayout.ALIGN_PARENT_RIGHT)
layoutParams = view.layoutParams as RelativeLayout.LayoutParams
layoutParams.leftMargin = (X - _xDelta).toInt()
layoutParams.topMargin = (Y - _yDelta).toInt()
layoutParams.rightMargin = 0
layoutParams.bottomMargin = 0
view.layoutParams = layoutParams
}
}
_root?.invalidate()
return true
}
但是当我触摸视图时,它会移动到左上角。我希望它只在我的手指触摸区域。我再次触摸后它工作正常。有什么解决办法吗?请帮忙。