android java

리사이클러뷰 및 리사이클러뷰 아답터, 뷰홀더 정리

안드로이드 샘플

 /**
 * 리스트뷰 생성을 위한 아답터 생성. 리사이클러뷰 아답터 상속 및 뷰홀더 지정.
 */
public class CustomAdapter extends RecyclerView.Adapter {

    /**로그캣 태그*/
    private static final String TAG = "CustomAdapter";
    /**데이터셋 정리*/
    private String[] mDataSet;

    // BEGIN_INCLUDE(recyclerViewSampleViewHolder)
    /**
     * 리사이클러뷰 사용할 뷰홀더 생성 및 상속
     */
    public static class ViewHolder extends RecyclerView.ViewHolder {
    /**텍스트뷰 선언*/
        private final TextView textView;
/**홀더 생성자.*/
        public ViewHolder(View v) {
            super(v);
            /**홀더 클릭리스터 등록.(리스트뷰 클릭)*/
            v.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    Log.d(TAG, "Element " + getAdapterPosition() + " clicked.");
                }
            });
            textView = (TextView) v.findViewById(R.id.textView);
        }

        public TextView getTextView() {
            return textView;
        }
    }
    // END_INCLUDE(recyclerViewSampleViewHolder)


    /**
     * Initialize the dataset of the Adapter.
     *
     * @param dataSet String[] containing the data to populate views to be used by RecyclerView.
     * 아답터에 데이터 등록
     */
    public CustomAdapter(String[] dataSet) {
        mDataSet = dataSet;
    }

    // BEGIN_INCLUDE(recyclerViewOnCreateViewHolder)
    // Create new views (invoked by the layout manager)
    @Override
    public ViewHolder onCreateViewHolder(ViewGroup viewGroup, int viewType) {
        // Create a new view.
/** 리스트뷰 생성을 위한 뷰 등록 */
        View v = LayoutInflater.from(viewGroup.getContext())
                .inflate(R.layout.text_row_item, viewGroup, false);

        return new ViewHolder(v);
    }
    // END_INCLUDE(recyclerViewOnCreateViewHolder)

    // BEGIN_INCLUDE(recyclerViewOnBindViewHolder)
    // Replace the contents of a view (invoked by the layout manager)
    @Override
    public void onBindViewHolder(ViewHolder viewHolder, final int position) {
        Log.d(TAG, "Element " + position + " set.");

        // Get element from your dataset at this position and replace the contents of the view
        // with that element
/**홀더로 생성된 뷰의 데이터 삽입*/
        viewHolder.getTextView().setText(mDataSet[position]);
    }
    // END_INCLUDE(recyclerViewOnBindViewHolder)

    // Return the size of your dataset (invoked by the layout manager)
    /**데이터의 크기 가져오기.*/
    @Override
    public int getItemCount() {
        return mDataSet.length;
    }
}


Activity 또는 Fragment 에서 


레이아웃 속성 정의.
정의한 데이터를 아답터 생성할때 데이터 삽입.
리사이클러뷰에 아답터 등록.





+ Recent posts