iT邦幫忙

0

android studio recyclerView adapter 多個類別 簡化

我在很多頁面都建立了recyclerView,每個adapter各寫了一個adapter,(還有監聽事件)
我還在只會寫類別的階段,請問我要怎麼把它簡化?(寫成介面?)
有哪一本書或網站可以幫助我?

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;

import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;

public class RecyclerViewAdapter extends RecyclerView.Adapter<RecyclerViewAdapter.ViewHolder> {

    RecyclerViewAdapter(){

    }

    class ViewHolder extends RecyclerView.ViewHolder{
        private TextView txtItem;

        ViewHolder(View itemView){
            super(itemView);
            txtItem=(TextView)itemView.findViewById(R.id.txtItem);
           
        }
    }

    @NonNull
    @Override
    public ViewHolder onCreateViewHolder(@NonNull ViewGroup viewGroup, int i) {
        View view = LayoutInflater.from(viewGroup.getContext())
                .inflate(R.layout.composite_table, viewGroup, false);
        return new ViewHolder(view);
        //return null;
    }

    @Override
    public void onBindViewHolder(@NonNull ViewHolder viewHolder, int i) {
        if (mOnItemClickListener != null) {
            holder.itemView.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    mOnItemClickListener.onItemClick(holder.itemView, position);

                 
                }
            });
        }
    }

    @Override
    public int getItemCount() {
        //return 3;
    }
    private OnItemClickListener mOnItemClickListener;
    public interface OnItemClickListener {
        void onItemClick(View view, int position);

        void onItemLongClick(View view, int position);
    }

    public void setOnItemClickListener(OnItemClickListener listener) {
        this.mOnItemClickListener = listener;
    }
}

1 個回答

0
GuanHongHuang
iT邦新手 5 級 ‧ 2019-10-19 10:06:32

可以把 ViewHolder 拉出去變成一個類別,Adapter 只留三個必寫的方法
onCreateViewHolderonBindViewHoldergetItemCount
還有一個公開的方法 setDataList 用來丟數據清單,看起來就會乾淨很多。

我要發表回答

立即登入回答