点击更换文字,长按移动
package com.zhangyu.mytouchevent;
import android.os.Bundle;
import android.os.Vibrator;
import android.support.constraint.ConstraintLayout;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.widget.FrameLayout;
import android.widget.TextView;
import java.util.Random;
public class MainActivity extends AppCompatActivity {
private static final String TAG = "MainActivity";
private TextView tvTitle;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
initView();
}
long timeDown, timeMove;
boolean isLongClick;
float downX, downY, moveX, moveY;
private void initView() {
tvTitle = (TextView) findViewById(R.id.tvTitle);
tvTitle.setOnTouchListener(new View.OnTouchListener() {
@Override
public boolean onTouch(View v, MotionEvent event) {
switch (event.getAction()) {
case MotionEvent.ACTION_DOWN:
Log.d(TAG, "onTouch: ACTION_DOWN");
timeDown = System.currentTimeMillis();
isLongClick = false;
downX = event.getRawX();
downY = event.getRawY();
break;
case MotionEvent.ACTION_MOVE:
Log.d(TAG, "onTouch: ACTION_MOVE");
timeMove = System.currentTimeMillis();
long durationMs = timeMove - timeDown;
if (durationMs > 500) {
vibrate();
isLongClick = true;
Log.d(TAG, "onTouch: isLongClick=" + isLongClick);
moveX = event.getRawX();
moveY = event.getRawY();
float dx = moveX - downX;
float dy = moveY - downY;
ViewGroup.MarginLayoutParams params = (FrameLayout.MarginLayoutParams) tvTitle.getLayoutParams();
params.leftMargin += dx;
params.topMargin += dy;
tvTitle.setLayoutParams(params);
downX = moveX;
downY = moveY;
}
break;
case MotionEvent.ACTION_UP:
Log.d(TAG, "onTouch: ACTION_UP");
if (!isLongClick)
tvTitle.setText(getRandomString(10));
break;
}
return true;
}
});
}
private void vibrate() {
if (!isLongClick) {
Vibrator vibrator = (Vibrator) this.getSystemService(this.VIBRATOR_SERVICE);
vibrator.vibrate(100);
}
}
public String getRandomString(int length) {
String base = "abcdefghijklmnopqrstuvwxyz0123456789";
Random random = new Random();
StringBuffer sb = new StringBuffer();
for (int i = 0; i < length; i++) {
int number = random.nextInt(base.length());
sb.append(base.charAt(number));
}
Log.e(TAG, "getRandomString: " + sb.toString());
return sb.toString();
}
}