美文网首页常用控件项目Android知识
安卓进阶第六篇之RecyclerView下拉刷新、左滑删除和It

安卓进阶第六篇之RecyclerView下拉刷新、左滑删除和It

作者: 起个牛逼的昵称 | 来源:发表于2016-09-07 23:54 被阅读3701次

    关于RecyclerView的介绍跟优点网上已经有很多了,这里我就不在啰嗦。

    </p>


    效果图

    1.配置gradle:

    compile 'com.jakewharton:butterknife:5.1.1'
    compile 'com.android.support:recyclerview-v7:23.1.0'
    

    2.Activity中的xml:

    activity_recycler_view_demo.xml
    
    <?xml version="1.0" encoding="utf-8"?>
    <RelativeLayout    xmlns:android="http://schemas.android.com/apk/res/android"    
    android:layout_width="match_parent"    
    android:layout_height="match_parent" >    
      <android.support.v4.widget.SwipeRefreshLayout        
       android:id="@+id/swipeRefreshLayout"        
       android:layout_width="wrap_content"        
       android:layout_height="wrap_content" >        
      <android.support.v7.widget.RecyclerView        
          xmlns:android="http://schemas.android.com/apk/res/android"           
          android:id="@+id/recycler_view"           
          android:layout_width="match_parent"            
          android:layout_height="match_parent"            
          android:layout_centerHorizontal="true"            
          android:layout_centerVertical="true"/>    
      </android.support.v4.widget.SwipeRefreshLayout>
    </RelativeLayout>
    

    3.Activity代码:

    public class RecyclerViewDemo extends AppCompatActivity implements NormalRecyclerViewAdapter.IonSlidingViewClickListener, SwipeRefreshLayout.OnRefreshListener {    
    @InjectView(R.id.swipeRefreshLayout)    
    SwipeRefreshLayout mSwipeRefreshLayout;    
    private String TAG = "RecyclerViewDemo";    
    @InjectView(R.id.recycler_view)    
    RecyclerView mRecyclerView;    
    NormalRecyclerViewAdapter adapter;    
    private static final int REFRESH_STATUS = 0;    
    private int j = 0;    
    @Override    
    protected void onCreate(Bundle savedInstanceState) {        
      super.onCreate(savedInstanceState);        
      setContentView(R.layout.activity_recycler_view_demo);        
      ButterKnife.inject(this);        
      initView();    
    }    
    private void initView() {        
      mRecyclerView.setLayoutManager(new LinearLayoutManager(this));//这里用线性显示 类似于listview
    //下面的两种方式自己可以试试看下效果就知道了
      //mRecyclerView.setLayoutManager(new GridLayoutManager(this, 2));//这里用线性宫格显示 类似于grid view
      //mRecyclerView.setLayoutManager(new     StaggeredGridLayoutManager(2,OrientationHelper.VERTICAL));//这里用线性宫格显示 类似于瀑布流        
      adapter = new NormalRecyclerViewAdapter(this);        
      //设置Item增加、移除动画        
      mRecyclerView.setItemAnimator(new DefaultItemAnimator());        
      mRecyclerView.setAdapter(adapter);        
      mSwipeRefreshLayout.setOnRefreshListener(this);
      mSwipeRefreshLayout.setColorSchemeResources(android.R.color.holo_blue_bright,   android.R.color.holo_green_light,                android.R.color.holo_orange_light, android.R.color.holo_red_light);        
    
      mSwipeRefreshLayout.post(new Runnable() {            
      @Override            
      public void run() {                
      mSwipeRefreshLayout.setRefreshing(true);           
       }        
      });        
      onRefresh();    
      }    
    @Override    
    public void onItemClick(View view, int position) {        
      Toast.makeText(RecyclerViewDemo.this, "单击" + position, Toast.LENGTH_SHORT).show();    
    }    
    @Override    
    public void onDeleteBtnCilck(View view, int position) {        
      Toast.makeText(RecyclerViewDemo.this, "删除" + position, Toast.LENGTH_SHORT).show();        
      adapter.removeData(position);    
    }    
    @Override   
    //下拉刷新的监听 
    public void onRefresh() {        
      refreshHandler.sendEmptyMessageDelayed(REFRESH_STATUS, 2000);    
    }    
    private Handler refreshHandler = new Handler()    
    {        
      public void handleMessage(Message msg) {            
      switch (msg.what) {                
      case REFRESH_STATUS:      
      //下拉刷新执行的操作,刷新数据              
      mSwipeRefreshLayout.setRefreshing(false);                    
      List<String> strings = new ArrayList<>();                    
      for (int i = 0; i < 10; i++) {                        
      j++;                        
      strings.add("测试" + j);                    
    }                    
      adapter.updateData(strings);                    
      break;            
    }        
    }
    };
    }
    

    4.适配器代码(NormalRecyclerViewAdapter)

    public class NormalRecyclerViewAdapter extends RecyclerView.Adapter<NormalRecyclerViewAdapter.MyViewHolder> implements SlidingButtonView.IonSlidingButtonListener {    
      private Context mContext;    
      private IonSlidingViewClickListener mIDeleteBtnClickListener;    
      private List<String> mDatas = new ArrayList<String>();    
      private SlidingButtonView mMenu = null;    
      public NormalRecyclerViewAdapter(Context context) {        
      mContext = context;        
      mIDeleteBtnClickListener = (IonSlidingViewClickListener) context;        
      for (int i = 0; i < 20; i++) {            
      mDatas.add("第"+i+"个测试");        
      }      
    }    
    public void updateData( List<String> mDatas){        
      this.mDatas = mDatas;        
      notifyDataSetChanged();    
    }    
    @Override    
    public int getItemCount() {        
      return mDatas.size();    
    }    
    @Override    
    public void onBindViewHolder(final MyViewHolder holder, int position) {        
      holder.textView.setText(mDatas.get(position));        //设置内容布局的宽为屏幕宽度        
      holder.layout_content.getLayoutParams().width = Utils.getScreenWidth(mContext);        
      holder.textView.setOnClickListener(new View.OnClickListener() {            
    @Override            
    public void onClick(View v) {                
      //判断是否有删除菜单打开                
      if (menuIsOpen()) {                    
      closeMenu();//关闭菜单                
      } else {                    
      int n = holder.getLayoutPosition();                      
      mIDeleteBtnClickListener.onItemClick(v, n);                
              }            
        }        
      });        
    holder.btn_Delete.setOnClickListener(new View.OnClickListener() {            
    @Override            
    public void onClick(View v) {                
      int n = holder.getLayoutPosition();                
      mIDeleteBtnClickListener.onDeleteBtnCilck(v, n);            
            }          
        });    
      }    
    @Override    
    public MyViewHolder onCreateViewHolder(ViewGroup arg0, int arg1) {        
      View view = LayoutInflater.from(mContext).inflate(R.layout.layout_item, arg0,false);        
      MyViewHolder holder = new MyViewHolder(view);        
      return holder;    
    }    
    class MyViewHolder extends RecyclerView.ViewHolder {        
      public TextView btn_Delete;        
      public TextView textView;        
      public ViewGroup layout_content;        
      public MyViewHolder(View itemView) {            
      super(itemView);            
      btn_Delete = (TextView) itemView.findViewById(R.id.tv_delete);            
      textView = (TextView) itemView.findViewById(R.id.text);            
      layout_content = (ViewGroup) itemView.findViewById(R.id.layout_content);            
      ((SlidingButtonView) itemView).setSlidingButtonListener(NormalRecyclerViewAdapter.this);        }    }    
     public void removeData(int position){        
      mDatas.remove(position);        
      notifyItemRemoved(position);    
    }    
    /**     * 删除菜单打开信息接收     */    
    @Override    
    public void onMenuIsOpen(View view) {        
      mMenu = (SlidingButtonView) view;    
    }    
    /**     
    * 滑动或者点击了Item监听     
    * @param slidingButtonView     
    */    
    @Override    
      public void onDownOrMove(SlidingButtonView slidingButtonView) {        
      if(menuIsOpen()){            
      if(mMenu != slidingButtonView){                
      closeMenu();            
          }        
        }    
      }    
    /**     * 关闭菜单     */    
    public void closeMenu() {        
      mMenu.closeMenu();        
      mMenu = null;    
    }    
    /**     * 判断是否有菜单打开     */    
    public Boolean menuIsOpen() {        
      if(mMenu != null){            
      return true;        
      }        
      return false;    
      }    
    public interface IonSlidingViewClickListener {        
      void onItemClick(View view,int position);        
      void onDeleteBtnCilck(View view,int position);    
    }
    }
    

    5.适配器的布局

    layout_item.xml
    
    <?xml version="1.0" encoding="utf-8"?>
    <com.example.littledemomarshal.littledemomarshal.SlidingButtonView    
      xmlns:android="http://schemas.android.com/apk/res/android"    
      android:layout_width="match_parent"    
      android:layout_height="60dp"    
      android:layout_marginBottom="1dp"    
      android:background="@android:color/white">    
      <RelativeLayout        
      android:layout_width="match_parent"        
      android:layout_height="match_parent" >        
        <RelativeLayout            
          android:id="@+id/layout_content"            
          android:layout_width="match_parent"            
          android:layout_height="match_parent">           
             <TextView                
              android:id="@+id/text"                
              android:layout_width="match_parent"                
              android:layout_height="match_parent"                
              android:background="@drawable/btn_click_black_havebackground"                
              android:gravity="center_vertical"                
              android:textColor="#DD000000"                
              android:textSize="16dp" />        
        </RelativeLayout>        
        <TextView            
          android:id="@+id/tv_delete"            
          android:layout_width="80dp"            
          android:layout_height="match_parent"            
          android:layout_toRightOf="@+id/layout_content"            
          android:background="@drawable/btn_click_red_havebackground"            
          android:gravity="center"            
          android:text="删 除"            
          android:textColor="#DDFFFFFF"/>    
        </RelativeLayout>
    </com.example.littledemomarshal.littledemomarshal.SlidingButtonView>
    

    6.适配器布局里面我们使用了一个自定义的HorizontalScrollView用来实现左滑删除(下面的代码是网上找的一个大神写的,自己稍微修改了一下)

    SlidingButtonView.java
    
    public class SlidingButtonView extends HorizontalScrollView   {    
      private TextView mTextView_Delete;    
      private int mScrollWidth;    
      private IonSlidingButtonListener mIonSlidingButtonListener;    
      private Boolean isOpen = false;    
      private Boolean once = false;
        
    public SlidingButtonView(Context context) {        
      this(context, null);    
      }   
    public SlidingButtonView(Context context, AttributeSet attrs) {        
      this(context, attrs,0);    
    }   
    public SlidingButtonView(Context context, AttributeSet attrs, int defStyleAttr) {        
      super(context, attrs, defStyleAttr);        
      this.setOverScrollMode(OVER_SCROLL_NEVER);    
    }    
    @Override    
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {        
      super.onMeasure(widthMeasureSpec, heightMeasureSpec);        
      if(!once){            
        mTextView_Delete = (TextView) findViewById(R.id.tv_delete);            
        once = true;       
       }    
    }    
    @Override    
    protected void onLayout(boolean changed, int l, int t, int r, int b) {        
      super.onLayout(changed, l, t, r, b);        
      if(changed){            
        this.scrollTo(0,0);            
        //获取水平滚动条可以滑动的范围,即右侧按钮的宽度              
        mScrollWidth = mTextView_Delete.getWidth();        
      }    
    }    
    @Override    
    public boolean onTouchEvent(MotionEvent ev) {        
      int action = ev.getAction();        
      switch (action) {            
      case MotionEvent.ACTION_DOWN:            
      case MotionEvent.ACTION_MOVE:                
      mIonSlidingButtonListener.onDownOrMove(this);                
      break;            
      case MotionEvent.ACTION_UP:            
      case MotionEvent.ACTION_CANCEL:                
      changeScrollx();                
      return true;            
      default:                
      break;        
    }        
    return super.onTouchEvent(ev);    } 
      
    /**     
    * 按滚动条被拖动距离判断关闭或打开菜单     
    */    
    public void changeScrollx(){        
      if(getScrollX() >= (mScrollWidth/2)){            
      this.smoothScrollTo(mScrollWidth, 0);            
      isOpen = true;            
      mIonSlidingButtonListener.onMenuIsOpen(this);        
      }else{            
      this.smoothScrollTo(0, 0);            
      isOpen = false;        
    }    
    }    
    /**    
     * 打开菜单     
    */    
    public void openMenu()    {        
      if (isOpen){            
      return;        
      }        
      this.smoothScrollTo(mScrollWidth, 0);        
      isOpen = true;        
      mIonSlidingButtonListener.onMenuIsOpen(this);    
    }    
    /**     
    * 关闭菜单     
    */    
    public void closeMenu()    {        
      if (!isOpen){            
      return;        
      }        
      this.smoothScrollTo(0, 0);        
      isOpen = false;    
    }    
    public void setSlidingButtonListener(IonSlidingButtonListener listener){        
      mIonSlidingButtonListener = listener;    
    }    
    public interface IonSlidingButtonListener{        
      void onMenuIsOpen(View view);        
      void onDownOrMove(SlidingButtonView slidingButtonView);    
    }
    

    个人觉得,有时候,直接上代码比语言描述有时候更有效。
    虽然是个简单的Demo,但希望对你的开发能有所帮助。

    相关文章

      网友评论

      • 岳齐:同学 有demo可以下载吗
      • e97b467041aa:你在适配器中context能强转成IonSlidingViewClickListener接口?activity能强转成接口?
        e97b467041aa:我的显示转换异常
      • Delicacy_ee85:有Demo地址吗
      • 锐萌萌OVO:QAQ 这个是什么啊 Utils.getScreenWidth(mContext);
        锐萌萌OVO:是 获取屏幕的宽度
      • 3ce2620b05f3:您好。我使用了你的方式实现了滑动。感觉很好用。我现在有个需求,是想通过一个参数,控制是否可以滑动。整个列表。不是单个item。我想了很久都没实现。不知道您有没好的建议 :smirk:
        起个牛逼的昵称: @程序猿男神 录屏软件录制的
        程序猿男神:效果图怎么生成的???
        起个牛逼的昵称:@一统 滑动整个列表,这个需求有点特殊啊,拒绝它,哈哈。。。

      本文标题:安卓进阶第六篇之RecyclerView下拉刷新、左滑删除和It

      本文链接:https://www.haomeiwen.com/subject/usmjettx.html