ABOUT ME

-

Today
-
Yesterday
-
Total
-
  • [안드로이드] RecyclerView 사용하기
    안드로이드(java)/기능 관련 2019. 1. 27. 15:02

    오늘은 안드로이드에서 자주 사용되는 recyclerView에 대해서 다뤄보겠습니다.


    간단한건 listView로 처리해도 되지만 카카오톡 대화 목록과같이


    이미지 하나와 글자 여러개로 조합된 내용들을 표시하고 싶다면


    listView로는 안되고 Custom ListView 로 해야하는데 성능적인 단점이 존재합니다.


    이러한 단점을 개선하고자 RecyclerView가 등장하였고 여러 다양한 화면을 구성할 수 있게 하였습니다.


    간단하게 구성하도록 하겠습니다.


    구성 및 소스코드는 아래 처럼 진행하시면 됩니다.


    안드로이드 버전이 올라가서 기존에 올렸던 support 패키지를 사용한 방식은 더이상 사용할 수 없게 되었습니다.


    androidx 패키지에 맞도록 다시 수정하여 등록하였습니다.




    < 구성할 layout >





    MainActivity에서는 300dp 만큼의 공간을 차지하도록 하고 그 안에서 recyclerView로 반복해서 보여질 내용들이 나타나도록 할겁니다.


    recyclerView의 내용은 이미지 하나와 글자 두개로 구성되어 있어요.


    - 코드 입력하기 전에 추가해야 할 내용 -

    Gradle Scripts 안에 build.gradle(Module: app) 에서 dependencies {...} 내부에 아래 내용을 추가해주셔야 recyclerview를 사용하실 수 있습니다.

    cardview는 모서리가 둥근 레이아웃을 만들고 싶어서 추가하였습니다.

    implementation 'androidx.recyclerview:recyclerview:1.0.0'
    implementation "com.google.android.material:material:1.0.0"

    compileSdkVersion이 29 라서 androidx 가 적용 되었습니다.





    - 소스 코드들 -


    < main_activity.xml >

    <?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:layout_width="match_parent"
    android:layout_height="300dp"
    android:orientation="vertical"
    tools:context=".MainActivity">

    <androidx.recyclerview.widget.RecyclerView
    android:id="@+id/rv"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    </androidx.recyclerview.widget.RecyclerView>

    </LinearLayout>



    < item.xml >

    <?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="100dp"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:orientation="vertical">

    <androidx.cardview.widget.CardView
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    app:cardCornerRadius="10dp">

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

    <ImageButton
    android:id="@+id/img"
    android:layout_width="0dp"
    android:layout_height="match_parent"
    android:layout_weight="1"/>

    <LinearLayout
    android:layout_width="0dp"
    android:layout_height="match_parent"
    android:layout_weight="3"
    android:orientation="vertical">

    <TextView
    android:id="@+id/tv1"
    android:layout_width="match_parent"
    android:layout_height="0dp"
    android:layout_weight="1"/>
    <TextView
    android:id="@+id/tv2"
    android:layout_width="match_parent"
    android:layout_height="0dp"
    android:layout_weight="1"/>
    </LinearLayout>

    </LinearLayout>


    </androidx.cardview.widget.CardView>

    </LinearLayout>


    layout 은 위와 같이 구성하면 끝입니다.




    이제 클래스들을 만들어줍니다.


    ViewHolder, recyclerview adapter, item class를 만듭니다.




    < Item.class >

    public class Item {
    int image;
    String tv1;
    String tv2;

    public Item(int image, String tv1, String tv2){
    this.image = image;
    this.tv1 = tv1;
    this.tv2 = tv2;
    }

    public int getImage() {
    return image;
    }

    public void setImage(int image) {
    this.image = image;
    }

    public String getTv1() {
    return tv1;
    }

    public void setTv1(String tv1) {
    this.tv1 = tv1;
    }

    public String getTv2() {
    return tv2;
    }

    public void setTv2(String tv2) {
    this.tv2 = tv2;
    }
    }


    생성자만 이용하실거면 getter와 setter는 안만드셔도 됩니다.





    < RecyclerViewHolder.class >, < RecyclerAdapter.class >



    public class RecyclerAdapter extends RecyclerView.Adapter<RecyclerViewHolder>{
    List<Item> list;

    public RecyclerAdapter(List<Item> list){
    this.list = list;
    }

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

    @Override
    public void onBindViewHolder(@NonNull RecyclerViewHolder holder, final int position) {
    holder.imageView.setImageResource(list.get(position).image);
    holder.textView1.setText(list.get(position).tv1);
    holder.textView2.setText(list.get(position).tv2);

    holder.textView1.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View v) {
    Toast.makeText(v.getContext(), list.get(position).tv1, Toast.LENGTH_SHORT).show();
    }
    });

    holder.textView2.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View v) {
    Toast.makeText(v.getContext(), list.get(position).tv2, Toast.LENGTH_SHORT).show();
    }
    });
    }

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

    class RecyclerViewHolder extends RecyclerView.ViewHolder {
    ImageView imageView;
    TextView textView1, textView2;

    public RecyclerViewHolder(@NonNull View itemView) {
    super(itemView);

    imageView = itemView.findViewById(R.id.img);
    textView1 = itemView.findViewById(R.id.tv1);
    textView2 = itemView.findViewById(R.id.tv2);
    }
    }




    < MainActivity.class >



    public class MainActivity extends AppCompatActivity {
    RecyclerView recyclerView;

    List<Item> list = new ArrayList<>();

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

    recyclerView = findViewById(R.id.rv);

    for (int i=0; i < 20; i++){
    list.add(new Item(R.mipmap.ic_launcher, "list " + i + "번째", "값 " + i));
    }

    LinearLayoutManager manager = new LinearLayoutManager(this, LinearLayoutManager.VERTICAL, false);
    recyclerView.setLayoutManager(manager);recyclerView.setHasFixedSize(false);
    recyclerView.setAdapter(new RecyclerAdapter(list));
    }
    }


    LinearLayoutManager 메서드의 두번째 파라미터에서 리사이클러뷰의 방향을 지정해줄 수 있습니다.


    LinearLayoutManager 말고 GridLayoutManager를 이용하면 그리드뷰로 나타낼 수도 있습니다.





    < 결과화면 >





    이상 RecyclerView 적용 방법이었습니다.











    댓글

Designed by Tistory.