前言
本学期学习了移动软件开发课程后,自己尝试实现了两个小功能,一个是利用OntouchListener()实现轨迹球滑动功能;一个是用Service实现一个简单播放器功能。
轨迹球
功能实现:
1.使用OnTouchListener()监听器实现一个轨迹球随着食指滑动运动;
2.我这边用了名字缩写代替轨迹球;
原理:
当按下手指的时候记录手指的坐标作为起始坐标,当手指抬起的时候把当前手指坐标与起始坐标对比,由此可以判断手指滑动的方向。
关于安卓监听器:
Android提供的基于事件监听接口有OnClickListener、OnLongClickListener、OnFocusChangeListener、OnKeyListener、OnTouchListener、OnCreateContextMenuListener等。
OnClickListener接口:该接口处理的是点击事件。在触摸模式下,是在某个View上按下并抬起的组合动作,而在键盘模式下,是某个View获得焦点后点击确定键或者按下轨迹球事件。
OnLongClickListener接口: OnLongClickListener接口与上述的OnClickListener接口原理基本相同,只是该接口为View长按事件的捕捉接口,即当长时间按下某个View时触发的事件。
OnFocusChangeListener接口:OnFocusChangeListener接口用来处理控件焦点发生改变的事件。如果注册了该接口,当某个控件失去焦点或者获得焦点时都会触发该接口中的回调方法。
OnKeyListener接口:是对手机键盘进行监听的接口,通过对某个View注册并监听,当View获得焦点并有键盘事件时,便会触发该接口中的回调方法。
OnTouchListener接口:是用来处理手机屏幕事件的监听接口,当为View的范围内触摸按下、抬起或滑动等动作时都会触发该事件。
OnCreateContextMenuListener接口:是用来处理上下文菜单显示事件的监听接口。该方法是定义和注册上下文菜单的另一种方式。
实现代码:
主要代码:
// An highlighted block
public class MainActivity extends AppCompatActivity {
private int screenW;
private int screenH;
public LinearLayout linearLayout;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
linearLayout = (LinearLayout) findViewById(R.id.root);
linearLayout.addView(new MyView(this));
}
class MyView extends View {
private Paint paint;
private float cx = 50;
private float cy = 50;
public MyView(Context context) {
super(context);
initPaint();
}
private void initPaint(){
paint = new Paint();
paint.setAntiAlias(true);
paint.setColor(Color.BLACK);
paint.setTextSize(40);
}
@Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
canvas.drawColor(Color.WHITE);
canvas.drawText("cc",cx,cy,paint);
}
@Override
public boolean onTouchEvent(MotionEvent event) {
switch (event.getAction()) {
case MotionEvent.ACTION_DOWN:
// 按下
cx = (int) event.getX();
cy = (int) event.getY();
// 通知重绘
postInvalidate();
break;
case MotionEvent.ACTION_MOVE:
// 移动
cx = (int) event.getX();
cy = (int) event.getY();
// 通知重绘
postInvalidate();
break;
case MotionEvent.ACTION_UP:
// 抬起
cx = (int) event.getX();
cy = (int) event.getY();
// 通知重绘
postInvalidate();
break;
}
return true;
} }
}
布局文件:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"