RecyclerView加载两套布局

一、想要实现加载两套不同的布局,只需在getItemViewType方法中返回不同的type,就可以在onCreateViewHolder 法中根据不同的type加载不同的布局,不同的布局,也同时也要实现不同的ViewHolder。onBindViewHolder方法也就可以根据不同的个布局进行不同的操作

/**
     * 适配器
     */
    class MyAdapter extends RecyclerView.Adapter {

        @Override
        public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
            View view = null;
            if (viewType == 0) {  //根据不同的viewtype,加载不同的布局
                view = LayoutInflater.from(mActivity).inflate(R.layout.item_date, parent,   		false);
                return new MyViewHolderOne(view);
            } else {
                view = LayoutInflater.from(mActivity).inflate(R.layout.item_sweep_word, 		parent, false);
                return new MyViewHolderTwo(view);
            }
        }


        @Override
        public int getItemViewType(int position) {
            if (position>10) {  //根据你的条件,返回不同的type
                return 0;
            } else {
                return 1;
            }

        }

        @Override
        public void onBindViewHolder(final RecyclerView.ViewHolder holder, final int position) {

            switch (getItemViewType(position)) {
                case 0:  //不同的布局,做不同的事
                    final MyViewHolderOne holderOne = (MyViewHolderOne) holder;
                    
                    break;
                case 1:
                    final MyViewHolderTwo holderTwo = (MyViewHolderTwo) holder;  
       	    }

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


        public class MyViewHolderOne extends RecyclerView.ViewHolder {

            TextView item_word_date;  //日期

            public MyViewHolderOne(View view) {
                super(view);
                item_word_date = (TextView) view.findViewById(R.id.item_word_date);
            }
        }


        public class MyViewHolderTwo extends RecyclerView.ViewHolder {

           TextView item_word;    //单词
            TextView item_word_mean;    //词义

            public MyViewHolderTwo(View view) {
                super(view);
                item_word = (TextView) view.findViewById(R.id.item_word);
                item_word_mean = (TextView) view.findViewById(R.id.item_word_mean);
            }
        }

    }

你可能感兴趣的:(RecyclerView加载两套布局)