View的事件体系
View的坐标系统
从Android3.0开始,View增加了额外的几个参数:
- x、y :其中x和y是View左上角的坐标
- translationX、translationY : translationX和translationY是View左上角相对于父容器的偏移量。translationX和translationY的默认值是0
View的四个基本的位置(left、right、buttom、top)参数一样,View也为它们提供了get/set方法,这几个参数的换算关系如下所示。
x=left+translationX
y=top+translationY
需要注意的是,View在平移的过程中,top和left表示的是原始左上角的位置信息,其值并不会发生改变,此时发生改变的是x、y、translationX和translationY这四个参数。
package com.ifredomer.viewdrawtest
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.widget.Button
import android.widget.SeekBar
import android.widget.TextView
import java.lang.StringBuilder
class MainActivity : AppCompatActivity() {
var translationX = 0
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
var button = findViewById<Button>(R.id.btn)
button.post {
translationX = button.translationX.toInt()
}
val seekBar = findViewById<SeekBar>(R.id.seek_bar)
val infoTv = findViewById<TextView>(R.id.info_tv)
seekBar.setOnSeekBarChangeListener(object : SeekBar.OnSeekBarChangeListener {
override fun onProgressChanged(seekBar: SeekBar?, progress: Int, fromUser: Boolean) {
if (fromUser) {
button.translationX = (translationX + progress * 2).toFloat()
var builder = StringBuilder()
builder.append(
"button left = ${button.left} right = ${button.right} top = ${button.top} bottom = ${button.bottom}\n" +
"translationX = ${button.translationX} translationY = ${button.translationY} x = ${button.x} y = ${button.y}"
)
infoTv.text = builder.toString()
}
}
override fun onStartTrackingTouch(seekBar: SeekBar?) {
}
override fun onStopTrackingTouch(seekBar: SeekBar?) {
}
})
}
}
布局如下:
<?xml version="1.0" encoding="utf-8"?>
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
<TextView
android:layout_margin="10dp"
android:id="@+id/info_tv"
android:layout_width="wrap_content"
android:layout_height="wrap_content"/>
<Button
android:id="@+id/btn"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:text="移动的按钮" />
<SeekBar
android:id="@+id/seek_bar"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_gravity="bottom"
android:layout_marginBottom="50dp" />
</FrameLayout>
结果演示:
本文部分资源引用自:Android开发艺术探索