개발언어/JAVA

안드로이드 앱 개발하기(recycler view 사용법)

우주먼지쪼가리 2020. 12. 12. 18:49
반응형

앞서,

recipes4dev.tistory.com/154

 

안드로이드 리사이클러뷰 기본 사용법. (Android RecyclerView)

1. 안드로이드 리사이클러뷰(RecyclerView) 리사이클러뷰(RecyclerView)는, "많은 수의 데이터 집합을, 제한된 영역 내에서 유연하게(flexible) 표시할 수 있도록 만들어주는 위젯"입니다. [안드로이드 개발

recipes4dev.tistory.com

읽으면 마음이 편해집니다.

 

 

//activity_main

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:orientation="vertical"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity">

    <androidx.recyclerview.widget.RecyclerView
        android:id="@+id/rv"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:scrollbarFadeDuration="0"
        android:scrollbarSize="5dp"
        android:scrollbarThumbVertical="@android:color/darker_gray"
        android:scrollbars="vertical"
        android:layout_weight="1">

    </androidx.recyclerview.widget.RecyclerView>

    <Button
        android:id="@+id/btn"
        android:layout_weight="8"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:text="추가"
        android:textSize="20dp">

    </Button>

</LinearLayout>
//한 컬럼

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
    xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent"
    android:layout_height="wrap_content">

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="horizontal">

        <ImageView
            android:id="@+id/iv_profile"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:src="@mipmap/ic_launcher"/>

        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:gravity="center_vertical"
            android:orientation="vertical">

            <TextView
                android:id="@+id/tv_name"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:text="엔훈의집"/>

            <TextView
                android:id="@+id/tv_content"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:text="리싸이클러뷰"/>

        </LinearLayout>

    </LinearLayout>



</LinearLayout>
//main data


package tipcalculator.gohool.recyclerview;

public class Maindata {

    //한 컬럼
    private int iv_profile;
    private String tv_name;
    private String tv_content;

    //구조 만들기 alt + insert
    public Maindata(int iv_profile, String tv_name, String tv_content) {
        this.iv_profile = iv_profile;
        this.tv_name = tv_name;
        this.tv_content = tv_content;
    }

    //getter and setter


    public int getIv_profile() {
        return iv_profile;
    }

    public void setIv_profile(int iv_profile) {
        this.iv_profile = iv_profile;
    }

    public String getTv_name() {
        return tv_name;
    }

    public void setTv_name(String tv_name) {
        this.tv_name = tv_name;
    }

    public String getTv_content() {
        return tv_content;
    }

    public void setTv_content(String tv_content) {
        this.tv_content = tv_content;
    }
}
// adapter


package tipcalculator.gohool.recyclerview;

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

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

import java.util.ArrayList;

public class MainAdapter extends RecyclerView.Adapter<MainAdapter.CusutmViewHolder> {

    //adapter: recyclerView.Adapter 를 상속하여 작성하며, 필요에 따라 ViewHolder를 생성하고 관리
    //alt + enter = implement 메소드



    //Maindata를 담을 arraylist
    private ArrayList<Maindata> arrayList;

    public MainAdapter(ArrayList<Maindata> arrayList) {
        this.arrayList = arrayList;
    }


    //리스트 내의 항목을 표시하기 위한 VIew를 생성, 해당 뷰를 관리(hold)할 viewhloder 생성하여 리텅
    @NonNull
    @Override
    public MainAdapter.CusutmViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {

        //viewType 형태의 아이템 뷰를 위한 뷰홀더 객체 생성, flate:XML코드를 객체화
        View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.item_list,parent,false);
        CusutmViewHolder holder = new CusutmViewHolder(view);

        return holder;
    }

    //바인드(데이터 표시, 생명 주기)
    @Override
    public void onBindViewHolder(@NonNull MainAdapter.CusutmViewHolder holder, int position) {
        //인자를 통해 전달된 viewholder에 position에 기반한 데이터를 표시한다.
        holder.iv_profile.setImageResource(arrayList.get(position).getIv_profile());
        holder.tv_name.setText(arrayList.get(position).getTv_name());
        holder.tv_content.setText(arrayList.get(position).getTv_content());

        //클릭, 롱클릭이 됐을 때를 구현
        holder.itemView.setTag(position);
        holder.itemView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String curName = holder.tv_name.getText().toString();
                Toast.makeText(v.getContext(), curName, Toast.LENGTH_LONG).show();
            }
        });
        //롱클릭하면 삭제할거임
        holder.itemView.setOnLongClickListener(new View.OnLongClickListener() {
            @Override
            public boolean onLongClick(View v) {
                LongClickRemove(holder.getAdapterPosition());

                return true;
            }
        });
    }

    //아이템의 전체 개수
    @Override
    public int getItemCount() {
        return (null != arrayList ? arrayList.size() : 0);
    }

    public void LongClickRemove(int position){
        try{
            //삭제
            arrayList.remove(position);
            //새로고침
            notifyItemRemoved(position);
        }catch (IndexOutOfBoundsException ex){
            ex.printStackTrace();
        }
    }



    //원하는 레이아웃 적용을 위해 reyclerView.ViewHolder를 상속하는 별도의 CLASS를 작성해야한다.
    public class CusutmViewHolder extends RecyclerView.ViewHolder {


        protected ImageView iv_profile;
        protected TextView tv_name;
        protected TextView tv_content;

        public CusutmViewHolder(@NonNull View itemView) {
            super(itemView);
            this.iv_profile = (ImageView) itemView.findViewById(R.id.iv_profile);
            this.tv_name = (TextView) itemView.findViewById(R.id.tv_name);
            this.tv_content = (TextView) itemView.findViewById(R.id.tv_content);

        }
    }
}
package tipcalculator.gohool.recyclerview;

import android.os.Bundle;
import android.view.View;
import android.widget.Button;

import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import java.util.ArrayList;

public class MainActivity extends AppCompatActivity {

    private ArrayList<Maindata> arrayList;
    private MainAdapter mainAdapter;
    private RecyclerView recyclerView;
    private LinearLayoutManager linearLayoutManager;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        recyclerView = (RecyclerView) findViewById(R.id.rv);
        linearLayoutManager = new LinearLayoutManager(this);
        recyclerView.setLayoutManager(linearLayoutManager);

        arrayList = new ArrayList<>();

        mainAdapter = new MainAdapter(arrayList);
        recyclerView.setAdapter(mainAdapter);

        Button btn = (Button) findViewById(R.id.btn);
        btn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Maindata maindata = new Maindata(R.mipmap.ic_launcher,"이름","리사이클러뷰");
                arrayList.add(maindata);
                //새로고침
                mainAdapter.notifyDataSetChanged();
            }
        });

    }
}

 

반응형