我在TextView
上使用了拖放功能,但是确实有效,但是当我将TextView
放在触摸的准确x和y位置(文本视图居中)时,我没有意识到TextView
在左上轴的x和y startof上,是因为这样我的放下无法按预期方式工作...当我放下时,如何更改TextView
轴居中或使他居中他吗?
它的作用: https://gph.is/2yxoPv9
我的代码:
class MainActivity : AppCompatActivity(), View.OnLongClickListener, View.OnDragListener {
private val TAG = MainActivity::class.java.getSimpleName()
private var llPinkLayout: RelativeLayout? = null
private var tvDragView: TextView? = null
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
setUpViews();
setListeners();
}
private fun setListeners() {
tvDragView?.setOnLongClickListener(this)
llPinkLayout?.setOnDragListener(this)
}
private fun setUpViews() {
llPinkLayout = findViewById<View>(R.id.ll_pinklayout) as RelativeLayout
tvDragView = findViewById<View>(R.id.tv_dropdrop) as TextView
}
override fun onDrag(view: View, dragEvent: DragEvent): Boolean {
Log.d(TAG, "onDrag: view->$view\n DragEvent$dragEvent")
when (dragEvent.action) {
DragEvent.ACTION_DRAG_ENDED -> {
Log.d(TAG, "onDrag: ACTION_DRAG_ENDED ")
return true
}
DragEvent.ACTION_DRAG_EXITED -> {
Log.d(TAG, "onDrag: ACTION_DRAG_EXITED")
return true
}
DragEvent.ACTION_DRAG_ENTERED -> {
Log.d(TAG, "onDrag: ACTION_DRAG_ENTERED")
return true
}
DragEvent.ACTION_DRAG_STARTED -> {
Log.d(TAG, "onDrag: ACTION_DRAG_STARTED")
return true
}
DragEvent.ACTION_DROP -> {
Log.d(TAG, "onDrag: ACTION_DROP")
val tvState = dragEvent.localState as View
Log.d(TAG, "onDrag:viewX" + dragEvent.x + "viewY" + dragEvent.y)
Log.d(TAG, "onDrag: Owner->" + tvState.parent)
val tvParent = tvState.parent as ViewGroup
tvParent.removeView(tvState)
val container = view as RelativeLayout
container.addView(tvState)
val contariner = view
tvParent.removeView(tvState)
tvState.x = dragEvent.x //the problem are there!
tvState.y = dragEvent.y //the problem are there!
view.addView(tvState)
view.setVisibility(View.VISIBLE)
return true
}
DragEvent.ACTION_DRAG_LOCATION -> {
Log.d(TAG, "onDrag: ACTION_DRAG_LOCATION")
return true
}
else -> return false
}
}
override fun onLongClick(v: View?): Boolean {
val dragShadowBuilder = View.DragShadowBuilder(v)
v?.startDrag(null, dragShadowBuilder, v, 0)
return true
}
}
答案 0 :(得分:0)
我已解决此问题,为此更改了x和y行:
DragEvent.ACTION_DROP -> {
Log.d(TAG, "onDrag: ACTION_DROP")
val tvState = dragEvent.localState as View
Log.d(TAG, "onDrag:viewX" + dragEvent.x + "viewY" + dragEvent.y)
Log.d(TAG, "onDrag: Owner->" + tvState.parent)
val tvParent = tvState.parent as ViewGroup
tvParent.removeView(tvState)
val container = view as RelativeLayout
container.addView(tvState)
val contariner = view
tvParent.removeView(tvState)
tvState.x = dragEvent.x - tvState.width/2 // FIXED
tvState.y = dragEvent.y - tvState.height/2 // FIXED
view.addView(tvState)
view.setVisibility(View.VISIBLE)
return true
}
我通过(touch x position) - (TextView width)/2
设置了TextView x
我通过(touch y position) - (TextView height)/2
设置了TextView y
这样我就可以将TextView
对准精确的触摸位置!