본문 바로가기

안드로이드

리사이클러뷰에 리스너 설정

반응형

activity_main.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="match_parent"
    android:orientation="vertical"
    tools:context=".MainActivity" >

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

 

person_item.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"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:orientation="vertical">

    <androidx.cardview.widget.CardView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        app:cardBackgroundColor="#FFFFFFFF"
        app:cardCornerRadius="10dp"
        app:cardElevation="5dp"
        app:cardUseCompatPadding="true" >

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

            <ImageView
                android:id="@+id/imageView"
                android:layout_width="80dp"
                android:layout_height="80dp"
                android:padding="5dp"
                app:srcCompat="@mipmap/ic_launcher" />

            <LinearLayout
                android:layout_width="match_parent"
                android:layout_height="match_parent"
                android:layout_margin="5dp"
                android:layout_weight="1"
                android:orientation="vertical">

                <TextView
                    android:id="@+id/textView"
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:text="이름"
                    android:textSize="30sp" />

                <TextView
                    android:id="@+id/textView2"
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:text="전화번호"
                    android:textColor="#FF0000FF"
                    android:textSize="25sp" />
            </LinearLayout>

        </LinearLayout>

    </androidx.cardview.widget.CardView>

</LinearLayout>

 

 

OnPersonItemClickListener.java

package com.example.a45_recyclerview2;

import android.view.View;

public interface OnPersonItemClickListener {
    public void onItemClick(PersonAdapter.ViewHolder holder, View view, int position);
}

 

Person.java

package com.example.a45_recyclerview2;

public class Person {
    String name;
    String mobile;

    public Person(String name, String mobile) {
        this.name = name;
        this.mobile = mobile;
    }

    public String getName() {
        return name;
    }

    public String getMobile() {
        return mobile;
    }

    public void setName(String name) {
        this.name = name;
    }

    public void setMobile(String mobile) {
        this.mobile = mobile;
    }
}

 

PersonAdapter.java

package com.example.a45_recyclerview2;

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

import androidx.recyclerview.widget.RecyclerView;

import java.util.ArrayList;

public class PersonAdapter extends RecyclerView.Adapter<PersonAdapter.ViewHolder> implements OnPersonItemClickListener {

    ArrayList<Person> items = new ArrayList<Person>();
    OnPersonItemClickListener listener;

    //    뷰홀더를 새로 만들어야할 때마다 이 메소드를 호출
//    뷰홀더와 그에 연결된 뷰를 생성하고 초기화하지만 뷰의 컨텐츠를 채우지 않음
    @Override
    public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {

        LayoutInflater inflater = LayoutInflater.from(parent.getContext());
        View itemView = inflater.inflate(R.layout.person_item, parent, false);

        return new ViewHolder(itemView, this);
    }

    //    데이터와 연결할 때 이 메소드를 호출
    @Override
    public void onBindViewHolder(ViewHolder holder, int position) {
        Person item = items.get(position);
        holder.setItem(item);
    }

    //    어댑터에서 관리하는 아이템의 개수를 반환
    @Override
    public int getItemCount() {
        return items.size();
    }

    public void addItem(Person item) {
        items.add(item);
    }

    public Person getItem(int position) {
        return items.get(position);
    }

    public void setItems(ArrayList<Person> items) {
        this.items = items;
    }

    public void setItem(int position, Person item) {
        items.set(position, item);
    }

    //    외부에서 리스너를 설정할 수 있도록 메소드 추가
    public void setOnItemClickListener(OnPersonItemClickListener listener) {
        this.listener = listener;
    }

    @Override
    public void onItemClick(ViewHolder holder, View view, int position) {
        listener.onItemClick(holder, view, position);
    }


    static class ViewHolder extends RecyclerView.ViewHolder {
        TextView textView;
        TextView textView2;

        //        뷰홀더 생성자로 전달되는 뷰 객체 참조
        public ViewHolder(View itemView, final OnPersonItemClickListener listener) {
            super(itemView);

            textView = itemView.findViewById(R.id.textView);
            textView2 = itemView.findViewById(R.id.textView2);

            itemView.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    int position = getAdapterPosition();

//                    아이템 뷰 클릭 시 OnPersonItemClickListener 인터페이스의 메소드 호출
                    if (listener != null) {
                        listener.onItemClick(ViewHolder.this, view, position);
                    }
                }
            });
        }

        public void setItem(Person item) {
            textView.setText(item.getName());
            textView2.setText(item.getMobile());
        }
    }
}

 

 

 

MainActivity

package com.example.a45_recyclerview2;

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

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

public class MainActivity extends AppCompatActivity {

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

        RecyclerView recyclerView = findViewById(R.id.recyclerView);

//        두 칼럼으로 표시되늰 격자 모양의 레이아웃으로 설정
        GridLayoutManager layoutManager = new GridLayoutManager(this, 2);
        recyclerView.setLayoutManager(layoutManager);

        PersonAdapter adapter = new PersonAdapter();

        adapter.addItem(new Person("김민수", "010-1000-1000"));
        adapter.addItem(new Person("김하늘", "010-2000-2000"));
        adapter.addItem(new Person("홍길동", "010-3000-3000"));
        adapter.addItem(new Person("aaa", "010-1000-1000"));
        adapter.addItem(new Person("bbb", "010-2000-2000"));
        adapter.addItem(new Person("ccc", "010-3000-3000"));
        adapter.addItem(new Person("ddd", "010-1000-1000"));
        adapter.addItem(new Person("eee", "010-2000-2000"));
        adapter.addItem(new Person("fff", "010-3000-3000"));
        adapter.addItem(new Person("ggg", "010-1000-1000"));
        adapter.addItem(new Person("hhh", "010-2000-2000"));
        adapter.addItem(new Person("iii", "010-3000-3000"));
        adapter.addItem(new Person("jjj", "010-1000-1000"));
        adapter.addItem(new Person("kkk", "010-2000-2000"));
        adapter.addItem(new Person("lll", "010-3000-3000"));

        recyclerView.setAdapter(adapter);

//        어댑터에 리스너 설정
        adapter.setOnItemClickListener(new OnPersonItemClickListener() {
            @Override
            public void onItemClick(PersonAdapter.ViewHolder holder, View view, int position) {
                Person item = adapter.getItem(position);
                Toast.makeText(getApplicationContext(), "아이템 선택됨 : " + item.getName(), Toast.LENGTH_SHORT).show();
            }
        });
    }
}

 

 

 

 

반응형

'안드로이드' 카테고리의 다른 글

트윈 애니메이션  (0) 2021.10.26
스피너  (0) 2021.10.26
리사이클러뷰  (0) 2021.10.26
새로운 레이아웃 만들기, 카드뷰 넣기  (0) 2021.10.26
새로운 뷰 만들기  (0) 2021.10.26