在recyclerview中每三项显示一次广告

时间:2019-04-18 11:08:40

标签: java android android-recyclerview

我已经实现了在每3个项目之后显示一次广告的代码,但是在4个项目恢复正常后才显示第一个项目

下面是我尝试实现的代码。

我想每3个项目展示一次广告。

我已经使用了两个常量变量来进行管理

private class AdsAdapter extends RecyclerView.Adapter<AdsAdapter.Holder> {

        List<Ads> list;
        List<String> stringList;
        private static final int AD_TYPE = 2;
        private static final int CONTENT_TYPE = 1;

        public AdsAdapter(List<Ads> list, List<String> stringList) {
            this.list = list;
            this.stringList = stringList;
        }

        @Override
        public int getItemViewType(int position) {

            if (position>1 && position % 4 == 0) {
                return AD_TYPE;
            }
            return CONTENT_TYPE;
        }

        @NonNull
        @Override
        public Holder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
            LayoutInflater layoutInflater = LayoutInflater.from(parent.getContext());
            Log.e("TYPE", viewType + "");

            View listItem;
            Holder viewHolder = null;
            switch (viewType) {
                case AD_TYPE:
                    listItem = 
             layoutInflater.inflate(R.layout.list_item1, parent, 
              false);
                    viewHolder = new Holder(listItem);
                    break;
                case CONTENT_TYPE:
                   listItem = 
           layoutInflater.inflate(R.layout.list_item, parent, 
             false);
                    viewHolder = new Holder(listItem);
                    break;
            }
            return viewHolder;
        }

        @Override
        public void onBindViewHolder(@NonNull Holder holder, int 
           position) {

            int viewType=getItemViewType(position);
            switch (viewType)
            {
                case AD_TYPE:
                    holder.imageView.setVisibility(View.VISIBLE);
                    break;
                case CONTENT_TYPE:
                    holder.textView.setVisibility(View.VISIBLE);
                    holder.textView.setText(stringList.get(position));
                    break;
            }

        }

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

        public class Holder extends RecyclerView.ViewHolder {
            TextView textView;
            ImageView imageView;

            public Holder(@NonNull View itemView) {
                super(itemView);
                textView = itemView.findViewById(R.id.tv_string);
                imageView = itemView.findViewById(R.id.iv);
            }
        }
    }

1 个答案:

答案 0 :(得分:0)

adapter位置从0开始,因此您必须做position+1

 @Override
 public int getItemViewType(int position) {

    if (position>1 && (position+1) % 4 == 0) {
            return AD_TYPE;
     }
     return CONTENT_TYPE;
 }