前面实现了界面向右滑动finish当前activity。
然后今天又想到了其实大可以不把activity演变成对话框形式,只需要处理activity的view的背景就行啦!然后就试了试,结果还真行。
getWindow().setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));
View decorView = getWindow().getDecorView() ;
decorView.setBackgroundColor(Color.TRANSPARENT);
((ViewGroup)decorView).getChildAt(0).setBackgroundColor(Color.TRANSPARENT);
通过在Oncreate执行上面代码便将activity的背景设置成透明的啦,即decorView .setX(x)之后,你可以看到下层的activity界面。
微信6.2也有左向右滑动finish,但是限制在api>=19才有这个功能。不过微信多了个下层界面偏移的动画。实现起来也不难。下面一起来介绍下。
为了让activity背景完全透明,光上面的代码还是不行的,还需要为activity指定如下的style。
[html] view plaincopy
@null
true
@null
这里不做多的介绍啦!这样activity其实已经有透明的底啦!现在只需要然activity随着滑动位移。当然是试用上面提到的getWindow().getDecorView()。setx(x)是activity的界面移动。现在只需要捕获touch事件即可。
下面是定制的layout,用于简单监听touch事件。
package com.czy.slideback;
import android.content.Context;
import android.util.AttributeSet;
import android.util.TypedValue;
import android.view.MotionEvent;
import android.widget.LinearLayout;
/**
* Created by nahuo16 on 2015/6/18.
*/
public class TouchLinearLayout extends LinearLayout {
private final int barHeight;
private OnTouchListener touchListener ;
private boolean shouldListener ;
private int side ;
private int downX, downY;
private int canBackSide ;
public TouchLinearLayout(Context context) {
this(context, null);
}
public TouchLinearLayout(Context context, AttributeSet attrs) {
this(context, attrs, 0);
}
public TouchLinearLayout(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
side = dip2px(context, 80) ;
canBackSide = dip2px(context, 20) ;
TypedValue value = new TypedValue();
context.getTheme().resolveAttribute(R.attr.actionBarSize, value, true);
barHeight = context.getResources().getDimensionPixelSize(value.resourceId);
}
private int dip2px(Context context, int dp) {
return (int) (context.getResources().getDisplayMetrics().density * dp + 0.5f);
}
@Override
public boolean onInterceptTouchEvent(MotionEvent ev) {
switch (ev.getAction()){
case MotionEvent.ACTION_DOWN:
downX = (int) ev.getX();
downY = (int) ev.getY();
shouldListener = downX < side && downY > barHeight ;
break ;
case MotionEvent.ACTION_MOVE:
if(shouldListener){
int x = (int) (ev.getX() - downX);
if( x> canBackSide && Math.abs(x / (ev.getY() - downY))>1.1f){
return true ;
}
}
break ;
case MotionEvent.ACTION_CANCEL:
case MotionEvent.ACTION_UP:
break ;
}
return false;
}
@Override
public boolean onTouchEvent(MotionEvent event) {
if(touchListener!=null)
touchListener.onTouch(this , event) ;
return true;
}
public void setOnTouchListener(OnTouchListener l){
touchListener = l ;
}
}
将这个线性布局做为根布局。(需要RelativeLayout?将上面的linearLayout换成RelativeLayout即可)。xml布局如下: