Search code examples
javaandroidbanner

How to add Startapp banner in recyclerview?


I find some problems of adding Startapp's banner on my application, so if anyone can help me to add it I will be appreciated. If anything is missed please let me know.

Mycode.java

 public ParseAdapter(ArrayList<ParseItem> parseItems, Context context) {
        this.parseItems = parseItems;
        this.context = context;
        dialog = new Dialog(context);
    @NonNull
    @Override
    public ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.parse_item, parent, false);
        return new ViewHolder(view);}
    @Override
    public void onBindViewHolder(@NonNull ViewHolder holder, int position) {
        ParseItem parseItem = parseItems.get(position);
        holder.textView.setText(parseItem.getTitle());
        holder.duration.setText(parseItem.getSongTime());
        holder.artist.setText(parseItem.getArtist());
        Glide.with(context).load(parseItem.getImgUrl()).into(holder.imageView);

    }

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

Solution

  • You need another layout for the "banner". Assume you need to add the banner as the top item in the recycler view.

    first is to add 1 to getItemCount:

    override public fun getItemCount() = parseItems.size + 1
    

    then override the getItemViewType function, let the adapter know which row need which layout:

    override public fun getItemViewType(position:Int) {
        if (position == 0)  // top row
            return R.layout.row_banner
        else
            return R.layout.parse_item
    }
    

    then create the view from the view type:

    override public fun onCreateViewHolder(parent:ViewGroup, viewType:Int) : ViewHolder 
    {
        val view = LayoutInflater.from(parent.getContext()).inflate(viewType, parent, false)
        return new ViewHolder(view)
    }
    

    note the viewType parameter is what you return in getItemViewType, usually I use the layout id directly.

    and then bind the rows:

    override public fun onBindViewHolder(hodler: ViewHolder holder, position:Int) {
        if (position == 0) {
            // the banner !
            return
        }
        ParseItem parseItem = parseItems.get(position - 1);
    
    }