自定義布局左右滑動,內含GridView
public class SlideLayout extends LinearLayout implements View.OnTouchListener {
/**
* 手指按下的橫坐標
*/
private float xDown;
/**
* 在被判定為滾動之前用戶手指可以移動的最大值。
*/
private int touchSlop;
private boolean leftViewShow = true;
private View lefter;
private ViewGroup.MarginLayoutParams lefterLayoutParams;
private int leftWidth;
private GridView gridView;
private boolean isSlided = false;
public SlideLayout(Context context) {
super(context);
init(context);
}
public SlideLayout(Context context, AttributeSet attrs) {
super(context, attrs);
init(context);
}
public SlideLayout(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
init(context);
}
private void init(Context context) {
touchSlop = ViewConfiguration.get(context).getScaledTouchSlop();
lefter = LayoutInflater.from(context).inflate(R.layout.lefter_layout, null, true);
addView(lefter, 0);
}
@Override
protected void onLayout(boolean changed, int l, int t, int r, int b) {
super.onLayout(changed, l, t, r, b);
lefterLayoutParams = (MarginLayoutParams) lefter.getLayoutParams();
leftWidth = lefter.getWidth();
gridView = (GridView) getChildAt(1);
gridView.setOnTouchListener(this);
}
@Override
public boolean onTouch(View v, MotionEvent event) {
int width = -leftWidth / 2;
switch (event.getAction()) {
case MotionEvent.ACTION_DOWN:
xDown = event.getRawX();
break;
case MotionEvent.ACTION_MOVE:
float xMove = event.getRawX();
int distance = (int) (xMove - xDown);
if (Math.abs(distance) < touchSlop) {
isSlided = false;
} else
isSlided = true;
// 要讓gridView失去焦點,否則被點擊的那一項會一直處于選中狀態
gridView.setPressed(false);
gridView.setFocusable(false);
gridView.setFocusableInTouchMode(false);
if (distance < 0) {
if (leftViewShow) {
lefterLayoutParams.leftMargin = distance / 3;
lefter.setLayoutParams(lefterLayoutParams);
}
}
if (distance > 0) {
if (!leftViewShow) {
lefterLayoutParams.leftMargin = distance / 3 - leftWidth;
lefter.setLayoutParams(lefterLayoutParams);
}
}
break;
case MotionEvent.ACTION_UP:
// 判斷leftView的坐標,如果隱藏的部分超過一半,就直接滑動過去全部隱藏
// 如果顯示的部分超過一半,也直接滑動過來直接顯示
if (lefterLayoutParams.leftMargin <= width) {
lefterLayoutParams.leftMargin = -leftWidth;
lefter.setLayoutParams(lefterLayoutParams);
leftViewShow = false;
} else if (lefterLayoutParams.leftMargin >= width) {
lefterLayoutParams.leftMargin = 0;
lefter.setLayoutParams(lefterLayoutParams);
leftViewShow = true;
}
// 解決onTouch和onClick的沖突
return isSlided;
}
return false;
}
}
最后編輯于 :
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。