我参考了这篇文章,我将它改了一下:
可动态布局的Android抽屉之基础
工程中需要这样的效果,左边和右边的Panel可以打开关闭:
我把左边和右边的Panel封装成2个类了。这里要特别注意,抽屉是需要“handler”的,我这里可以把任何View都看成“handler”,使用setBindView(View bindView)方法进行绑定“handler”。这样做的好处是“把手”可以独立于抽屉,可以任意控制把手的位置,而不需要把手跟着抽屉移动!
先看左边的Panel:
可动态布局的Android抽屉之基础
工程中需要这样的效果,左边和右边的Panel可以打开关闭:
我把左边和右边的Panel封装成2个类了。这里要特别注意,抽屉是需要“handler”的,我这里可以把任何View都看成“handler”,使用setBindView(View bindView)方法进行绑定“handler”。这样做的好处是“把手”可以独立于抽屉,可以任意控制把手的位置,而不需要把手跟着抽屉移动!
先看左边的Panel:
import android.content.Context;
import android.os.AsyncTask;
import android.view.View;
import android.widget.LinearLayout;
public class LeftPanel extends LinearLayout{
/**每次自动展开/收缩的范围*/
private final static int SPEED=20;
private int MAX_WIDTH=0;
private Context mContext;
public LeftPanel(Context context,int width,int height) {
super(context);
this.mContext=context;
//设置Panel本身的属性
LayoutParams lp=new LayoutParams(width, height);
lp.leftMargin=-lp.width;
MAX_WIDTH=Math.abs(lp.leftMargin);
this.setLayoutParams(lp);
}
/**
*
* @param context
* @param width
* @param height
* @param bindView
* @param contentView
*/
public LeftPanel(Context context,int width,int height,View bindView,View contentView) {
this(context,width,height);
setBindView(bindView);
setContentView(contentView);
}
/**
* 把View放在Panel中
* @param v
*/
public void setContentView(View v){
this.addView(v);
}
/**
* 绑定触发动画的View
* @param bindView
*/
public void setBindView(View bindView){
bindView.setOnClickListener(new OnClickListener(){
@Override
public void onClick(View v) {
LayoutParams lp = (LayoutParams) getLayoutParams();
if (lp.leftMargin < 0)// CLOSE的状态
new AsynMove().execute(new Integer[] { SPEED });// 正数展开
else if (lp.leftMargin >= 0)// OPEN的状态
new AsynMove().execute(new Integer[] { -SPEED });// 负数收缩
}
});
}
class AsynMove extends AsyncTask<Integer, Integer, Void> {
@Override
protected Void doInBackground(Integer... params) {
int times;
if (MAX_WIDTH % Math.abs(params[0]) == 0)// 整除
times = MAX_WIDTH / Math.abs(params[0]);
else
times = MAX_WIDTH / Math.abs(params[0]) + 1;// 有余数
for (int i = 0; i < times; i++) {
publishProgress(params);