前言:上下滑动列表时,toolbar跟着隐藏和显示,这种效果在google系应用中比较频繁出现,比如google plus。
google plus效果:
现在以ListVIew列表实现(两种方式):
一,使用ListView的方法addHeaderView(headerView);
1,build.gradle:
dependencies { compile fileTree(dir: 'libs', include: ['*.jar']) testCompile 'junit:junit:4.12' compile 'com.android.support:appcompat-v7:23.1.1' compile 'com.android.support:design:23.1.1' }
2,主界面布局
activity_main.xml
<?xml version="1.0" encoding="utf-8"?> <android.support.design.widget.CoordinatorLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" tools:context="com.science.listscroll.MainActivity"> <include layout="@layout/content_main" /> <android.support.v7.widget.Toolbar android:id="@+id/toolbar" android:layout_width="match_parent" android:layout_height="wrap_content" android:background="?attr/colorPrimary" android:fitsSystemWindows="true" android:theme="@style/AppTheme.AppBarOverlay" app:popupTheme="@style/AppTheme.PopupOverlay" /> <android.support.design.widget.FloatingActionButton android:id="@+id/fab" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_gravity="bottom|end" android:layout_margin="@dimen/fab_margin" android:src="@android:drawable/ic_dialog_email" /> </android.support.design.widget.CoordinatorLayout>
content_main.xml
<?xml version="1.0" encoding="utf-8"?> <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto" android:layout_width="match_parent" android:layout_height="match_parent"> <ListView android:id="@+id/list" android:layout_width="match_parent" android:layout_height="match_parent" /> </RelativeLayout>3,item布局item.xml
<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="match_parent" android:background="#eeeeee"> <TextView android:id="@+id/text" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_margin="16dp" android:textSize="20sp" /> </LinearLayout>
4,主题逻辑
package com.science.listscroll; import android.animation.Animator; import android.animation.AnimatorSet; import android.animation.ObjectAnimator; import android.content.Intent; import android.graphics.Color; import android.os.Bundle; import android.support.design.widget.FloatingActionButton; import android.support.design.widget.Snackbar; import android.support.v7.app.AppCompatActivity; import android.support.v7.widget.Toolbar; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.view.ViewGroup; import android.widget.AbsListView; import android.widget.AdapterView; import android.widget.ArrayAdapter; import android.widget.ListView; import android.widget.Toast; import java.util.ArrayList; /** * @author 幸运Science-陈土燊 * @description ListView列表滑动时隐藏显示view(类似google plus),方法一:listview.addHeaderView(headerView); * @school University of South China * @company wiwide.com * @email [email protected],[email protected] * @data 2015/11/29 */ public class MainActivity extends AppCompatActivity { private ListView mListView; private Toolbar mToolbar; private FloatingActionButton mActionButton; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); mToolbar = (Toolbar) findViewById(R.id.toolbar); setSupportActionBar(mToolbar); mActionButton = (FloatingActionButton) findViewById(R.id.fab); mActionButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG) .setAction("Action", null).show(); } }); initVeiw(); initListener(); } private void initVeiw() { mListView = (ListView) findViewById(R.id.list); // 添加头部 View headerView = new View(this); headerView.setLayoutParams(new AbsListView.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, (int) getResources().getDimension(R.dimen.abc_action_bar_default_height_material) + getStatusHeight())); headerView.setBackgroundColor(Color.parseColor("#eeeeee")); mListView.addHeaderView(headerView); // 加载数据 ArrayAdapter adapter = new ArrayAdapter(this, R.layout.item, R.id.text, getData()); mListView.setAdapter(adapter); } // 状态栏高度 private int getStatusHeight() { int result = 0; int resourceId = getResources().getIdentifier("status_bar_height", "dimen", "android"); if (resourceId > 0) { result = getResources().getDimensionPixelSize(resourceId); } return result; } private void initListener() { mListView.setOnScrollListener(new AbsListView.OnScrollListener() { int lastposition = 0; // 上一次在屏幕里可见的第一个item在整个listview的位置 int state = SCROLL_STATE_IDLE; // 默认状态滚动停止 @Override public void onScrollStateChanged(AbsListView view, int scrollState) { state = scrollState; } @Override public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) { View firstView = view.getChildAt(firstVisibleItem); /** * 1,firstVisibleItem == 0:当前屏幕第一个可见item是整体listview的第一个item时 * 2,firstView == null:列表为空时;或者列表不为空时第一个item距离顶部的距离为0,说明已到达顶部 */ if (firstVisibleItem == 0 && (firstView == null || firstView.getTop() == 0)) { animateBack(); } if (firstVisibleItem > 0) { // 即向上滑动列表 if (firstVisibleItem > lastposition) { animateHide(); } // 即向下滑动列表 if (firstVisibleItem < lastposition) { animateBack(); } } lastposition = firstVisibleItem; } }); mListView.setOnItemClickListener(new AdapterView.OnItemClickListener() { @Override public void onItemClick(AdapterView<?> parent, View view, int position, long id) { Toast.makeText(MainActivity.this, "item:" + (position - 1), Toast.LENGTH_SHORT).show(); } }); } private String[] getData() { String[] str = new String[30]; for (int i = 0; i < 30; i++) { str[i] = "item" + i; } return str; } // 恢复动画 private AnimatorSet mAnimatorSetBack; private void animateBack() { // 取消其他动画 if (mAnimatorSetHide != null && mAnimatorSetHide.isRunning()) { mAnimatorSetHide.cancel(); } if (mAnimatorSetBack != null && mAnimatorSetBack.isRunning()) { } else { mAnimatorSetBack = new AnimatorSet(); ObjectAnimator animateHeader = ObjectAnimator.ofFloat(mToolbar, "translationY", mToolbar.getTranslationY(), 0f); ObjectAnimator animateFooter = ObjectAnimator.ofFloat(mActionButton, "translationY", mActionButton.getTranslationY(), 0f); ArrayList<Animator> animators = new ArrayList<>(); animators.add(animateHeader); animators.add(animateFooter); mAnimatorSetBack.setDuration(300); mAnimatorSetBack.playTogether(animators); mAnimatorSetBack.start(); } } // 隐藏动画 private AnimatorSet mAnimatorSetHide; private void animateHide() { // 取消其他动画 if (mAnimatorSetBack != null && mAnimatorSetBack.isRunning()) { mAnimatorSetBack.cancel(); } if (mAnimatorSetHide != null && mAnimatorSetHide.isRunning()) { } else { mAnimatorSetHide = new AnimatorSet(); ObjectAnimator animateHeader = ObjectAnimator.ofFloat(mToolbar, "translationY", mToolbar.getTranslationY(), -mToolbar.getHeight()); ObjectAnimator animateFooter = ObjectAnimator.ofFloat(mActionButton, "translationY", mActionButton.getTranslationY(), mActionButton.getHeight() + mActionButton.getBottom()); ArrayList<Animator> animators = new ArrayList<>(); animators.add(animateHeader); animators.add(animateFooter); mAnimatorSetHide.setDuration(300); mAnimatorSetHide.playTogether(animators); mAnimatorSetHide.start(); } } @Override public boolean onCreateOptionsMenu(Menu menu) { // Inflate the menu; this adds items to the action bar if it is present. getMenuInflater().inflate(R.menu.menu_main, menu); return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { // Handle action bar item clicks here. The action bar will // automatically handle clicks on the Home/Up button, so long // as you specify a parent activity in AndroidManifest.xml. int id = item.getItemId(); //noinspection SimplifiableIfStatement if (id == R.id.baseadapter) { Intent intent = new Intent(MainActivity.this, ListViewSecActivity.class); startActivity(intent); return true; } if (id == R.id.recycleview) { return true; } return super.onOptionsItemSelected(item); } }
5,关键在通过ListView的addHeaderView()方法,添加一个toolbar+status高度的头部item,然后在Scroll方法里处理listview滑动,逻辑比较好理解。
二,通过BaseAdapter里添加头部
1,其它和直接通过addHeaderView()方法添加头部差不多,头部直接在BaseAdapter里添加
class MyAdapter extends BaseAdapter { private static final int HEADER_ITEM = 0; private static final int NORMAL_ITEM = 1; private Context mContext; private String[] mSts; public MyAdapter(Context context, String[] strs) { mContext = context; mSts = strs; } @Override public int getCount() { return mSts.length + 1; } @Override public Object getItem(int position) { return position; } @Override public long getItemId(int position) { return position; } @Override public int getItemViewType(int position) { if (position == 0) { return HEADER_ITEM; } return NORMAL_ITEM; } @Override public int getViewTypeCount() { return 2; } @Override public View getView(int position, View convertView, ViewGroup parent) { ViewHolder viewHolder = null; int viewType = getItemViewType(position); if (convertView == null) { if (viewType == HEADER_ITEM) { convertView = new View(mContext); convertView.setLayoutParams(new AbsListView.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, (int) mContext.getResources().getDimension(R.dimen.abc_action_bar_default_height_material) + getStatusHeight(mContext))); convertView.setBackgroundColor(Color.parseColor("#eeeeee")); viewHolder = new ViewHolder(convertView, viewType); } else { convertView = LayoutInflater.from(mContext).inflate(R.layout.item, parent, false); viewHolder = new ViewHolder(convertView, viewType); } convertView.setTag(viewHolder); } else { viewHolder = (ViewHolder) convertView.getTag(); } if (viewType == NORMAL_ITEM) { viewHolder.textView.setText(mSts[position - 1]); } return convertView; } private int getStatusHeight(Context context) { int result = 0; int resourceId = context.getResources().getIdentifier("status_bar_height", "dimen", "android"); if (resourceId > 0) { result = context.getResources().getDimensionPixelSize(resourceId); } return result; } } class ViewHolder { TextView textView; public ViewHolder(View view, int viewType) { if (viewType != 0) { textView = (TextView) view.findViewById(R.id.text); } } }
最终效果图(Android4.4的MIUI7):
代码http://download.csdn.net/detail/u013260551/9310959