以下代码是实现自定义图片滑动的上下左右时发生的变化及处理:
效果图:
1、自定义类
public class Myview extends ImageView {
private float mDownX,mDownY;
private float mMoveX,mMoveY;
public changbackgroutcolor mchang;
//在代码里实例化
public Myview(Context context) {
this(context,null);
}
//在布局里声明,并且用到自定义属性的时候调用
public Myview(Context context, AttributeSet attrs) {
this(context, attrs,0);
}
//在布局里声明,并且用到自定义样式的时候调用
public Myview(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
}
public interface changbackgroutcolor{
public abstract void changeleft();
public abstract void changelregth();
public abstract void changetop();
public abstract void changebuttom();
}
//监听view的触摸事件
@Override
public boolean onTouchEvent(MotionEvent event) {
int action=event.getAction();
switch (action) {
//按下
case MotionEvent.ACTION_DOWN:
mDownX=event.getRawX();
mDownY=event.getRawY();
break;
//手指在屏幕上移动
case MotionEvent.ACTION_MOVE:
mMoveX=event.getRawX();
mMoveY=event.getRawY();
event.getRawY();
break;
//手指重屏幕上抬起
case MotionEvent.ACTION_UP:
if(Math.abs(mMoveX-mDownX)>Math.abs(mMoveY-mDownY)){
//横着滑
if(mMoveX-mDownX>0){
//右滑
mchang.changelregth();
}else{
//左滑
mchang.changeleft();
}
}else{
//纵着滑
if(mMoveY-mDownY>0){
//下滑
mchang.changebuttom();
}else{
//上滑
mchang.changetop();
}
}
break;
}
return true;
}
}
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/id"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:gravity="center"
tools:context=".MainActivity" >
<com.example.imgview.Myview
android:id="@+id/mv_iv"
android:layout_width="200dp"
android:layout_height="200dp"
android:src="@drawable/aa" />
</RelativeLayout>
控件中使用自定义imgview类
3、Mainactivity代码:
public RelativeLayout mroot;
private Myview imgview;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mroot=(RelativeLayout) findViewById(R.id.id);
imgview=(Myview) findViewById(R.id.mv_iv);
imgview.mchang=new changbackgroutcolor() {
//上
@Override
public void changetop() {
// TODO Auto-generated method stub
mroot.setBackgroundColor(Color.parseColor("#FFFF00"));
Toast.makeText(MainActivity.this, "上滑动", Toast.LENGTH_LONG).show();
}
//右
@Override
public void changelregth() {
mroot.setBackgroundColor(Color.parseColor("#FF0000"));
Toast.makeText(MainActivity.this, "右滑动", Toast.LENGTH_LONG).show();
}
//左
@Override
public void changeleft() {
mroot.setBackgroundColor(Color.parseColor("#00ff00"));
Toast.makeText(MainActivity.this, "左滑动", Toast.LENGTH_LONG).show();
}
//下
@Override
public void changebuttom() {
mroot.setBackgroundColor(Color.parseColor("#ff00ff"));
Toast.makeText(MainActivity.this, "下滑动", Toast.LENGTH_LONG).show();
}
};
}