본문 바로가기

안드로이드/코드

[안드로이드] 리싸이클러뷰 아이템 클릭시 이벤트 발생 시키기

반응형

 

 

 

itemclick_title

 

 

 

리싸이클러뷰의 아이템을 클릭했을 때 원하는 이벤트를 발생시키기 위해서는 해당 리사이클러뷰의 어댑터에서 액티비티에서 인터페이스로 전달을 받아야 이벤트를 감지하고 원하는 이벤트를 발생시킬 수 있습니다.

간단한 예제를 만들어보겠습니다.

 

 

 

 

itemclick_1

 

 

1. activity_main.xml

<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">

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

 

 


2. person_item.xml

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:orientation="vertical"
    android:layout_width="match_parent"
    android:layout_height="wrap_content">


    <android.support.v7.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">
            <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:orientation="vertical"
                android:layout_margin="5dp"
                android:layout_weight="1">
                <TextView
                    android:id="@+id/nameText"
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:text="이름"
                    android:textSize="20sp"/>
                <TextView
                    android:id="@+id/mobileText"
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:text="전화번호"
                    android:textColor="#FF0000FF"
                    android:textSize="15sp"/>



            </LinearLayout>

        </LinearLayout>

    </android.support.v7.widget.CardView>


</LinearLayout>

 

리싸이클러뷰 안의 각 아이템에 대한 뷰를 그리는 파일입니다.

원하는 대로 커스텀해서 사용하시면 될 것 같습니다.

 

 

 

3.Person.java

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 void setName(String name) {
        this.name = name;
    }

    public String getMobile() {
        return mobile;
    }

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

 

 

 

4. PersonAdaper.java

import android.support.annotation.NonNull;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

import java.util.ArrayList;

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

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

    @NonNull
    @Override
    public ViewHolder onCreateViewHolder(@NonNull ViewGroup viewGroup, int i) {
        LayoutInflater inflater = LayoutInflater.from(viewGroup.getContext());
        View itemView = inflater.inflate(R.layout.person_item,viewGroup,false);
        return new ViewHolder(itemView,this);
    }

    @Override
    public void onBindViewHolder(@NonNull ViewHolder viewHolder, int position) {
        Person item = items.get(position);
        viewHolder.setItem(item);
    }

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

    public void setOnItemClicklistener(OnPersonItemClickListener listener){
        this.listener = listener;
    }

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

    static class ViewHolder extends RecyclerView.ViewHolder{
        TextView nameText;
        TextView mobileText;

        public ViewHolder(View itemView, final OnPersonItemClickListener listener){
            super(itemView);

            nameText = itemView.findViewById(R.id.nameText);
            mobileText = itemView.findViewById(R.id.mobileText);

            itemView.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    int position = getAdapterPosition();
                    if(listener != null){
                        listener.onItemClick(ViewHolder.this, v, position);
                    }
                }
            });
        }

        public void setItem(Person item){
            nameText.setText(item.getName());
            mobileText.setText(item.getMobile());
        }
    }

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

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

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

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

 

 

 

5. OnPersonItemClickListener

import android.view.View;

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

 

 

 

6. MainActivity.java

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.widget.LinearLayout;
import android.widget.Toast;

public class MainActivity extends AppCompatActivity {

    RecyclerView recyclerView;
    PersonAdapter adapter;

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

        recyclerView = findViewById(R.id.recyclerView);

        
        LinearLayoutManager layoutManager1 =
                new LinearLayoutManager(recyclerView.getContext());

        recyclerView.setLayoutManager(layoutManager1);
        adapter = new PersonAdapter();

        adapter.addItem(new Person("김민수","010-1000-1000"));
        adapter.addItem(new Person("김하늘","010-2000-2000"));
        adapter.addItem(new Person("박현","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_LONG).show();
            }
        });
    }
}

 

 

간단하게 예제를 만들어봤는데요.

 

원하시는 다른 이벤트가 있으시다면 MainActivity.java에서 onItemClick 함수를 통해서 변경해서 사용하시면 됩니다.

 

도움이 되셨길 바라겠습니다.

반응형