可左右两侧挤压傍边布局的Android抽屉

这篇博客分享了一个Android应用中实现的双向挤压效果的抽屉布局,通过 StretchDemo.zip 示例代码,展示了如何创建两个可以相互挤压的Button,下载次数达到127次。
摘要由CSDN通过智能技术生成
我参考了这篇文章,我将它改了一下:
可动态布局的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);
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值