1. 程式人生 > >RecyclerView的Adapter標準寫法

RecyclerView的Adapter標準寫法

package adapter;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
import com.example.administrator.mynotebook.R;
import java.util.List;
import com.example.administrator.mynotebook.ui.date.Note;
public class MyAdapter extends RecyclerView.Adapter<MyAdapter.ViewHolder>{
    
    //此例子以記事本為例,每個Item包含兩個控制元件,ImageView和TextView
    //需提前建立實體類Note,定義兩個成員變數和相應的get、set方法
    private List<Note> mNoteList;
    public MyAdapter(List<Note> mNoteList){
        this.mNoteList = mNoteList;
    }

    @Override
    public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.note_item,parent,false);
        ViewHolder viewHolder = new ViewHolder(view);
        return viewHolder;
    }

    @Override
    public void onBindViewHolder(ViewHolder holder, int position) {
        Note note = mNoteList.get(position);
        holder.item_img.setImageResource(note.getId());
        holder.item_context.setText(note.getContext());
    }

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

    public class ViewHolder extends RecyclerView.ViewHolder {
        private ImageView item_img;
        private TextView item_context;

        public ViewHolder(View itemView) {
            super(itemView);
            item_img =  itemView.findViewById(R.id.item_img);
            item_title =  itemView.findViewById(R.id.item_context);
        }
    }
}