Android抽屉效果(使用LayoutParams来移动View的位置)

package com.siyehuazhilian.masterslider;

import android.app.Activity;
import android.os.Bundle;
import android.view.MotionEvent;
import android.view.WindowManager;
import android.widget.LinearLayout;

public class MainActivity extends Activity {
	private LinearLayout menuLayout, contentLayout;
	private LinearLayout.LayoutParams menuLayoutParams, contentLayoutParams;

	// 左边缘
	private int leftEdge;

	// 滑动因子
	private boolean speedFlag = true;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
		// 菜单栏
		menuLayout = (LinearLayout) findViewById(R.id.menu);
		// 内容栏
		contentLayout = (LinearLayout) findViewById(R.id.content);

		// 得到父控件
		menuLayoutParams = (LinearLayout.LayoutParams) menuLayout
				.getLayoutParams();
		contentLayoutParams = (LinearLayout.LayoutParams) contentLayout
				.getLayoutParams();

		WindowManager windowManager = (WindowManager) getSystemService(WINDOW_SERVICE);
		int width = windowManager.getDefaultDisplay().getWidth();
		// 菜单栏隐藏起来.内容栏设置为0内容栏必须设置,否则无法随菜单栏的移动而移动,会被压缩或拉伸
		leftEdge = menuLayoutParams.width = width - 80;
		menuLayoutParams.leftMargin = -menuLayoutParams.width;
		contentLayoutParams.width = width;
		contentLayoutParams.leftMargin = 0;
	}

	private int startX;
	private int distance;

	@Override
	public boolean onTouchEvent(MotionEvent event) {

		switch (event.getAction()) {
		case MotionEvent.ACTION_DOWN:
			startX = (int) event.getRawX();
			break;
		case MotionEvent.ACTION_MOVE:
			if (speedFlag) {// 每10毫秒次响应一次移动
				// 计算手指移动的距离
				distance = (int) ((event.getRawX() - startX) / 5);

				// 如果手指移动的距离加上menu左边距的大小没有超过屏幕且大于初始的位置,就移动它
				if (menuLayoutParams.leftMargin + distance <= 0
						&& menuLayoutParams.leftMargin + distance > -leftEdge) {
					menuLayoutParams.leftMargin += distance;
					menuLayout.setLayoutParams(menuLayoutParams);
				}
				speedFlag = false;
			} else {
				controlspeed();
			}
			break;
		case MotionEvent.ACTION_UP:
			// 手指离开时,判断移动的宽度,如果大于一半,就显示出来,否则隐藏
			if (leftEdge - -menuLayoutParams.leftMargin > leftEdge / 2) {
				menuLayoutParams.leftMargin = 0;
			} else {
				menuLayoutParams.leftMargin = -leftEdge;
			}
			menuLayout.setLayoutParams(menuLayoutParams);
			break;

		default:
			break;

		}
		return true;
	}

	private void controlspeed() {
		try {
			Thread.sleep(30);
		} catch (InterruptedException e) {
			e.printStackTrace();
		}
		speedFlag = true;
	}
}

//源码分享
//http://pan.baidu.com/s/1o6mBPHo


你可能感兴趣的:(Android抽屉效果(使用LayoutParams来移动View的位置))