ListView的基本使用

生活本来就不容易啊,而我们的不努力只会让生活变得更加无赖。

相信大家在学习过程当中对ListView一定不会陌生,基本我们要用到列表时第一时间会想到它,虽然在Android5.0时Google推出了RecyclerView企图取代它,而且在这段期间内RecyclerView基本上已经可以满足取代ListView的能力(我始终觉得秒现瀑布流效果非常牛),但我觉得还是需要认真学习ListView,这两天结合《Android群英传》的学习,写一下ListView的学习笔记。

ListView的简单使用:

  • activity_main.xml
```
* 代码使用:
 * 适配器MyAdapter

public class MyAdapter extends BaseAdapter{

private List list;
private LayoutInflater inflater;

public MyAdapter(Context context ,List list) {

    this.list = list;
    inflater = LayoutInflater.from(context);
}

@Override
public int getCount() {
    return list.size();
}

@Override
public Object getItem(int i) {
    return null;
}

@Override
public long getItemId(int i) {
    return i;
}

@Override
public View getView(int i, View view, ViewGroup viewGroup) {
    viewHolder viewHolder = null;
    if (view == null){
        viewHolder = new viewHolder();
        view = inflater.inflate(R.layout.view_holder,null);
        viewHolder.textView  = (TextView) view.findViewById(R.id.text_view);
        view.setTag(viewHolder);
    }else{
        viewHolder = (MyAdapter.viewHolder) view.getTag();
    }

    viewHolder.textView.setText(list.get(i));
    return view;
}

class viewHolder{
    TextView textView;
}

}```

  • MainActivity.java
public class MainActivity extends AppCompatActivity implements View.OnTouchListener {

    private List list ;
    private MyAdapter adapter;
    private ListView listView;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        initView();
    }

    private void initView() {
        listView = (ListView) findViewById(R.id.list_view);
        list = initList();
        adapter = new MyAdapter(this,list);
        listView.setAdapter(adapter);

        //设置ListView为空时的显示图片
        listView.setEmptyView(findViewById(R.id.emptyImage));
        //滑动监听事件
        listView.setOnTouchListener(this);
        //设置点击事件
        listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView adapterView, View view, int position, long l) {

            }
        });
    }
    private List initList() {
        List mdatas = new ArrayList<>();
        for (int i = 'A';i<'z';++i){
            mdatas.add(""+(char)i);
        }
        return mdatas;
    }
    @Override
    public boolean onTouch(View view, MotionEvent motionEvent) {

        switch (motionEvent.getAction()){
            case MotionEvent.ACTION_DOWN:
                //触摸时调用                Toast.makeText(this,"Down",Toast.LENGTH_SHORT).show();
            break;
            case MotionEvent.ACTION_MOVE:
                //滑动时调用
                Toast.makeText(this,"Move",Toast.LENGTH_SHORT).show();
            break;
            case MotionEvent.ACTION_UP:
                //离开时调用
                Toast.makeText(this,"Up",Toast.LENGTH_SHORT).show();
            break;
        }

        return false;
    }
}```
* 效果

![easyUsing.gif](http://upload-images.jianshu.io/upload_images/2605454-19b3cdbb5a5deff7.gif?imageMogr2/auto-orient/strip)
------
### 常用属性:
-  设置ListView为空时的显示布局

//设置ListView为空时的显示图片
listView.setEmptyView(findViewById(R.id.emptyImage));```

  • 动态增加数据及设置ListView位置
    /**
     * 动态增加
     */
    public void btnAdd(){
        list.addAll(Arrays.asList("Hello","Hi","WelCome"));
        adapter.notifyDataSetChanged();
        listView.setSelection(0);
    }```
- 具有弹性的ListView

/**
*修改overScrollBy方法中的maxOverScrollY值
/
private int mMaxOverSrcollY = 5;
//适配分辨率
private void getmMaxOverSrcollY(){
DisplayMetrics metrics = context.getResources().getDisplayMetrics();
float density = metrics.density;
mMaxOverSrcollY = (int) (density
mMaxOverSrcollY);
}

@Override
protected boolean overScrollBy(int deltaX, int deltaY,
                               int scrollX, int scrollY,
                               int scrollRangeX, int scrollRangeY, 
                               int maxOverScrollX, int maxOverScrollY, 
                               boolean isTouchEvent) {
    return super.overScrollBy(deltaX, deltaY, scrollX,
            scrollY, scrollRangeX, scrollRangeY, maxOverScrollX,
            mMaxOverSrcollY, isTouchEvent);
}```
  • 为ListView设置滑动时Toolbar的隐藏
    其实逻辑很简单,就是为ListView设置headView,然后借助OnTouchListener获取滑动点的坐标改变大小,实现滑上滑下距离的判断.最后借助简单的动画实现隐藏和出现.

  • 代码

//获取系统认为的最低滑动距离
    private float mTouchSlop;
    //定义两个变量进行两次滑动距离的判断
    private float mFirstY , mCurrentY;
    //声明flag标志Toolbar状态
    private int direction;
    //声明boolean判断状态
    private boolean mShow;
    private Toolbar mToorbar;
    private Animator mAnimator;
  mToorbar = (Toolbar) findViewById(R.id.tool_bar);
        setSupportActionBar(mToorbar);
        //添加headView
        View head = new View(this);
        head.setLayoutParams(new AbsListView.LayoutParams(AbsListView.LayoutParams.MATCH_PARENT,
                (int) getResources().getDimension(R.dimen.abc_action_bar_default_height_material)));
        listView.addHeaderView(head);
        //获取最低滑动距离
        mTouchSlop = ViewConfiguration.get(this).getScaledTouchSlop();
 @Override
    public boolean onTouch(View view, MotionEvent motionEvent) {

        switch (motionEvent.getAction()){
            case MotionEvent.ACTION_DOWN:
                //触摸时调用,获取第一次位置
                mFirstY = motionEvent.getY();
            break;
            case MotionEvent.ACTION_MOVE:
                //滑动时调用
                mCurrentY = motionEvent.getY();
                if (mCurrentY - mFirstY > mTouchSlop){
                    direction = 0;//向下滑
                }else if (mFirstY - mCurrentY >mTouchSlop){
                    direction = 1;//向上滑
                }
                if (direction == 1){
                    if (mShow){
                        toolbarAnim(0);//隐藏
                        mShow = !mShow;
                    }
                }else if (direction == 0){
                    if (!mShow){
                        toolbarAnim(1);
                        mShow = !mShow;
                    }
                }
            break;
            case MotionEvent.ACTION_UP:
                //离开时调用
            break;
        }

        return false;
    }
    //控制head布局状态
    private void toolbarAnim(int flag) {
        if (mAnimator != null && mAnimator.isRunning()){
            mAnimator.cancel();
        }
        if (flag == 0){
            mAnimator = ObjectAnimator.ofFloat(mToorbar,"translationY",
                    mToorbar.getTranslationY(),0);
        }else {
            mAnimator = ObjectAnimator.ofFloat(mToorbar,"translationY",
                    mToorbar.getTranslationY(),mToorbar.getHeight());
        }
        mAnimator.start();
    }```
  
 * 效果


![head.gif](http://upload-images.jianshu.io/upload_images/2605454-95bd553b9901fad5.gif?imageMogr2/auto-orient/strip)
### 常见拓展
在学习ListView的,顺便学习了一下Hyman的一篇技术博客,是关于仿QQ实现左划删除的效果的,其实代码的逻辑也很简单,就是利用事件分发机制实现手势的判断,利用dispatchTouchEvent以及onTouchEvent这两个方法对手势进行判断,最后利用Button对所在Item进行delete
* 整体预览

![Paste_Image.png](http://upload-images.jianshu.io/upload_images/2605454-0753a480c0a920dd.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240)
 * xml文件
   * enter_ainm.xml


android:fromXScale="0.0"
android:toXScale="1.0"
android:fromYScale="0.0"
android:toYScale="1.0"
android:pivotX="50%"
android:pivotY="50%"
android:duration="200"/>
android:interpolator="@android:anim/decelerate_interpolator"
android:fromAlpha="0.0"
android:toAlpha="1.0"
android:duration="200"/>
```

  • exit_ain.xml

    
    
```
  * del_btn.xml

```

  • activity_main.xml


    
    
```
  * style.xml

```

  • MyListView.java
public class MyListView extends ListView {
    
    /**
     * 用户滑动的最小距离
     */
    private int mTouchSlop;

    /**
     * 是否响应滑动
     */
    private boolean isSliding;

    /**
     * 手指按下时的x坐标
     */
    private int FirstX;
    /**
     * 手指按下时的y坐标
     */
    private int FirstY;
    /**
     * 手指移动时的x坐标
     */
    private int NextX;
    /**
     * 手指移动时的y坐标
     */
    private int NextY;

    private LayoutInflater mInflater;

    private PopupWindow mPopupWindow;
    private int mPopupWindowHeight;
    private int mPopupWindowWidth;

    private Button mDelBtn;
    /**
     * 为删除按钮提供一个回调接口
     */
    private DelButtonClickListener mListener;

    /**
     * 当前手指触摸的View
     */
    private View mCurrentView;

    /**
     * 当前手指触摸的位置
     */
    private int mCurrentViewPos;

    /**
     * 必要的一些初始化
     *
     */
    public MyListView(Context context, AttributeSet attrs) {
        super(context, attrs);

        mInflater = LayoutInflater.from(context);
        mTouchSlop = ViewConfiguration.get(context).getScaledTouchSlop();

        View view = mInflater.inflate(R.layout.del_btn, null);
        mDelBtn = (Button) view.findViewById(R.id.btn_del);
        mPopupWindow = new PopupWindow(view, LinearLayout.LayoutParams.WRAP_CONTENT,
                LinearLayout.LayoutParams.WRAP_CONTENT);
        /**
         * 先调用下measure,否则拿不到宽和高
         */
        mPopupWindow.getContentView().measure(0, 0);
        mPopupWindowHeight = mPopupWindow.getContentView().getMeasuredHeight();
        mPopupWindowWidth = mPopupWindow.getContentView().getMeasuredWidth();
    }

    @Override
    public boolean dispatchTouchEvent(MotionEvent ev) {
        int x = (int) ev.getX();
        int y = (int) ev.getY();
        switch (ev.getAction()) {

            case MotionEvent.ACTION_DOWN:
                FirstX = x;
                FirstY = y;
                /**
                 * 如果当前popupWindow显示,则直接隐藏,然后屏蔽ListView的touch事件的下传
                 */
                if (mPopupWindow.isShowing()) {
                    dismissPopWindow();
                    return false;
                }
                // 获得当前手指按下时的item的位置
                mCurrentViewPos = pointToPosition(FirstX, FirstY);
                // 获得当前手指按下时的item
                View view = getChildAt(mCurrentViewPos - getFirstVisiblePosition());
                mCurrentView = view;
                break;
            case MotionEvent.ACTION_MOVE:
                NextX = x;
                NextY = y;
                int dx = NextX - FirstX;
                int dy = NextY - FirstY;
                /**
                 * 判断是否是从右到左的滑动
                 */
                if (NextX < FirstX && Math.abs(dx) > mTouchSlop && Math.abs(dy) < mTouchSlop) {
                    isSliding = true;
                }
                break;
        }
        return super.dispatchTouchEvent(ev);
    }

    @Override
    public boolean onTouchEvent(MotionEvent ev) {
        int action = ev.getAction();
        /**
         * 如果是从右到左的滑动才相应
         */
        if (isSliding) {
            switch (action) {
                case MotionEvent.ACTION_MOVE:

                    int[] location = new int[2];
                    // 获得当前item的位置x与y
                    mCurrentView.getLocationOnScreen(location);
                    // 设置popupWindow的动画
                    mPopupWindow.setAnimationStyle(R.style.btn_del_Animotion);
                    mPopupWindow.update();
                    mPopupWindow.showAtLocation(mCurrentView, Gravity.START | Gravity.TOP,
                            location[0] + mCurrentView.getWidth(), location[1] + mCurrentView.getHeight() / 2
                                    - mPopupWindowHeight / 2);
                    // 设置删除按钮的回调
                    mDelBtn.setOnClickListener(new OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            if (mListener != null) {
                                mListener.clickHappend(mCurrentViewPos);
                                mPopupWindow.dismiss();
                            }
                        }
                    });

                    break;
                case MotionEvent.ACTION_UP:
                    isSliding = false;

            }
            // 相应滑动期间屏幕itemClick事件,避免发生冲突
            return true;
        }

        return super.onTouchEvent(ev);
    }

    /**
     * 隐藏popupWindow
     */
    private void dismissPopWindow() {
        if (mPopupWindow != null && mPopupWindow.isShowing()) {
            mPopupWindow.dismiss();
        }
    }

    public void setDelButtonClickListener(DelButtonClickListener listener) {
        this.mListener = listener;
    }

    public interface DelButtonClickListener {
        public void clickHappend(int position);
    }
}```
  * MainActivity.java

public class MainActivity extends AppCompatActivity {

private MyListView listView;
private ArrayAdapter adapter;
private List list;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    listView =(MyListView) findViewById(R.id.delete_listview);
    list = new ArrayList<>();
    for (int i = 1;i<100;++i){
        list.add(""+i);
    }
    adapter = new ArrayAdapter<>(this,android.R.layout.simple_list_item_1,list);
    listView.setAdapter(adapter);

    listView.setDelButtonClickListener(new MyListView.DelButtonClickListener() {
        @Override
        public void clickHappend(int position) {
            adapter.remove(adapter.getItem(position));
            adapter.notifyDataSetChanged();
        }
    });
    listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
        @Override
        public void onItemClick(AdapterView adapterView, View view, int position, long l) {                Toast.makeText(MainActivity.this,position+"onClick",Toast.LENGTH_SHORT).show();
        }
    });
}

}```

  • 代码如上,其实这相当大部分是模仿hyman的代码,不过出于学习的目的.所以写在自己的笔记.HongYang博客传送门
    http://blog.csdn.net/lmj623565791/
  • 效果
ListView的基本使用_第1张图片
delete.gif

如果觉得这篇文章有所错漏,麻烦指出,交流学习共同进步。

你可能感兴趣的:(ListView的基本使用)