XScrollView 自定义组件,使得被包含在其中的组件可以滑动,并且滑动后可以弹回到开始滑动的位置XScrollView
package org.busyboy.view;
import android.content.Context;
import android.util.AttributeSet;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;
import android.widget.LinearLayout;
public class XScrollView extends LinearLayout {
private float mLastY = 1;
private String TAG = XScrollView.class.getName();
private float margin =0 ;
private final static float OFFSET_RADIO = 1.8f;
public XScrollView(Context context) {
super(context);
}
public XScrollView(Context context, AttributeSet attrs) {
super(context, attrs);
}
@Override
public boolean onTouchEvent(MotionEvent ev) {
if (mLastY == -1) {
mLastY = ev.getRawY();
}
switch (ev.getAction()) {
case MotionEvent.ACTION_DOWN:
mLastY = ev.getRawY();
break;
case MotionEvent.ACTION_MOVE:
final float deltaY = ev.getRawY() - mLastY;
mLastY = ev.getRawY();
margin += deltaY;
updateHeaderHeight(margin);
break;
default:
mLastY = -1; // reset
resetHeaderHeight();
break;
}
return true;
}
private void resetHeaderHeight() {
Log.e(TAG , "resetHeaderHeight");
Log.e(TAG , "count:"+ this.getChildCount());
View child = this.getChildAt(0);
LinearLayout.LayoutParams param = (LayoutParams) child.getLayoutParams();
param.topMargin = 0;
child.setLayoutParams(param);
margin=0;
}
private void updateHeaderHeight(float f) {
Log.e(TAG , "updateHeaderHeight");
Log.e(TAG , "count:"+ this.getChildCount());
View child = this.getChildAt(0);
LinearLayout.LayoutParams param = (LayoutParams) child.getLayoutParams();
param.topMargin = (int) (f*OFFSET_RADIO);
child.setLayoutParams(param);
}
}
Demo:
<?xml version="1.0" encoding="utf-8"?>
<org.busyboy.view.XScrollView xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/xListView"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:background="#ff0000"
android:orientation="vertical" >
<LinearLayout
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:background="#f0f0f0"
android:gravity="center"
android:orientation="vertical" >
<ImageView
android:id="@+id/iv"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginBottom="20dp"
android:src="@drawable/ic_launcher" />
<EditText
android:id="@+id/username"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginBottom="10dp"
android:ems="10"
android:hint="@string/username" >
<requestFocus />
</EditText>
<EditText
android:id="@+id/pass"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginBottom="10dp"
android:ems="10"
android:hint="@string/pass"
android:inputType="textPassword" />
<Button
android:id="@+id/login"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginBottom="10dp"
android:text="@string/login" />
</LinearLayout>
</org.busyboy.view.XScrollView>