<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">
<ListView
android:id="@+id/main_list_view"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
/>
<android.support.v7.widget.Toolbar
android:id="@+id/main_bar"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:background="@color/std_color_A"
/>
</RelativeLayout>
public class MainActivity extends BaseActivity{
private static final String TAG = MainActivity.class.getSimpleName();
private Toolbar mMainToolbar = null;
private ListView mMainListView = null;
private float mStartY = 0, mLastY = 0, mLastDeltaY;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mMainToolbar = (Toolbar)this.findViewById(R.id.main_bar);
this.setSupportActionBar(mMainToolbar);
mMainListView = (ListView)this.findViewById(R.id.main_list_view);
final View header = LayoutInflater.from(this).inflate(R.layout.layout_header, null);//这个header高度要与toolbar相同
mMainListView.addHeaderView(header);
mMainListView.setAdapter(new AudioAdapter(this));
mMainListView.setOnTouchListener(new View.OnTouchListener() {
@Override
public boolean onTouch(View v, MotionEvent event) {
final float y = event.getY();
float translationY = mMainToolbar.getTranslationY();
switch (event.getAction()) {
case MotionEvent.ACTION_DOWN:
mStartY = y;
mLastY = mStartY;
break;
case MotionEvent.ACTION_MOVE:
float mDeltaY = y - mLastY;
float newTansY = translationY + mDeltaY;
if (newTansY <= 0 && newTansY >= -mMainToolbar.getHeight()) {
mMainToolbar.setTranslationY(newTansY);
}
mLastY = y;
mLastDeltaY = mDeltaY;
break;
case MotionEvent.ACTION_UP:
ObjectAnimator animator = null;
Log.d(TAG, "mLastDeltaY=" + mLastDeltaY);
if (mLastDeltaY < 0 && mMainListView.getFirstVisiblePosition() > 1) {
Log.v(TAG, "listView.first=" + mMainListView.getFirstVisiblePosition());
animator = ObjectAnimator.ofFloat(mMainToolbar, "translationY", mMainToolbar.getTranslationY(), -mMainToolbar.getHeight());
} else {
animator = ObjectAnimator.ofFloat(mMainToolbar, "translationY", mMainToolbar.getTranslationY(), 0);
}
animator.setDuration(100);
animator.start();
animator.setInterpolator(AnimationUtils.loadInterpolator(MainActivity.this, android.R.interpolator.linear));
break;
}
return false;
}
});
}
}