头像收起---ImageViewDraft

activity_main.xml

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context="com.example.draftimage.MainActivity" >
    <ImageView
        android:id="@+id/iv_draft"
        android:layout_width="fill_parent"
        android:layout_height="200dp"
        android:background="@drawable/logo"/>
</RelativeLayout>

MainActivity

package com.example.draftimage;

import android.app.Activity;
import android.os.Bundle;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnTouchListener;
import android.view.ViewTreeObserver;
import android.view.ViewTreeObserver.OnGlobalLayoutListener;
import android.widget.ImageView;
import android.widget.Toast;

public class MainActivity extends Activity implements OnTouchListener {
	private int lastY;
	private ImageView iv_draft;
	private int ivHeight;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
		iv_draft = (ImageView) findViewById(R.id.iv_draft);
		iv_draft.setOnTouchListener(this);

		ViewTreeObserver vto = iv_draft.getViewTreeObserver();

		vto.addOnGlobalLayoutListener(new OnGlobalLayoutListener() {
			@Override
			public void onGlobalLayout() {
				ivHeight = iv_draft.getMeasuredHeight();
			}
		});
	}

	@Override
	public boolean onTouch(View v, MotionEvent event) {

		switch (event.getAction()) {
		case MotionEvent.ACTION_DOWN:
			lastY = (int) event.getRawY();
			break;
		case MotionEvent.ACTION_MOVE:
			int dy = (int) event.getRawY() - lastY;

			int top = v.getTop() + dy;
			int bottom = v.getBottom() + dy;
			if (top < -ivHeight + ivHeight / 3) {
				top = -ivHeight + ivHeight / 3;
				bottom = ivHeight / 3;
			}
			if (bottom > ivHeight) {
				bottom = ivHeight;
				top = 0;
			}
			v.layout(0, top, iv_draft.getWidth(), bottom);
			lastY = (int) event.getRawY();
			break;
		case MotionEvent.ACTION_UP:
			break;
		}

		return true;
	}
}



你可能感兴趣的:(头像收起---ImageViewDraft)