본문 바로가기

모바일 프로그래밍(Android Studio)

RecyclerView에서 하나의 행을 삭제하기

◎ 예시)

<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout 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"
    tools:context=".MainActivity">

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:orientation="vertical"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintHorizontal_bias="1.0"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        app:layout_constraintVertical_bias="0.0">

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

            <LinearLayout
                android:layout_width="wrap_content"
                android:layout_height="114dp"
                android:orientation="vertical">

                <EditText
                    android:id="@+id/editName"
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:ems="10"
                    android:hint="이름 입력"
                    android:inputType="text" />

                <EditText
                    android:id="@+id/editPhone"
                    android:layout_width="match_parent"
                    android:layout_height="57dp"
                    android:ems="10"
                    android:hint="전화번호 입력"
                    android:inputType="phone" />

            </LinearLayout>

            <Button
                android:id="@+id/btnSave"
                android:layout_width="match_parent"
                android:layout_height="match_parent"
                android:layout_margin="20dp"
                android:backgroundTint="@color/white"
                android:text="저장"
                android:textColor="@color/black"
                android:textSize="20sp" />
        </LinearLayout>

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

<?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="horizontal">

    <androidx.cardview.widget.CardView
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_marginLeft="10dp"
        android:layout_marginTop="5dp"
        android:layout_marginRight="10dp"
        android:layout_marginBottom="5dp"
        android:layout_weight="5">

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

            <LinearLayout
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_weight="5"
                android:orientation="vertical">

                <TextView
                    android:id="@+id/txtName"
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:text="이름" />

                <TextView
                    android:id="@+id/txtPhone"
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:text="전화번호" />
            </LinearLayout>

            <ImageView
                android:id="@+id/imgDelete"
                android:layout_width="40dp"
                android:layout_height="40dp"
                android:layout_weight="1"
                app:srcCompat="@drawable/baseline_clear_24" />

        </LinearLayout>
    </androidx.cardview.widget.CardView>

</LinearLayout>

package com.example.callbook.model;

public class Call {
        public String name;
        public String phone;
}

package com.example.callbook.adapter;

import android.content.Context;
import android.content.DialogInterface;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AlertDialog;
import androidx.recyclerview.widget.RecyclerView;

import com.example.callbook.MainActivity;
import com.example.callbook.R;
import com.example.callbook.model.Call;

import java.util.ArrayList;


import android.view.LayoutInflater;
import android.view.ViewGroup;


public class CallAdapter extends RecyclerView.Adapter<CallAdapter.ViewHolder> {

        Context context;
        ArrayList<Call> callList;

        ImageView imgDelete;

        public CallAdapter(Context context, ArrayList<Call> callList) {
                this.context = context;
                this.callList = callList;
            }

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

            @Override
            public void onBindViewHolder(@NonNull ViewHolder holder, int position) {
                Call call = callList.get(position); // position는 해당 위치를 나타낸다
                holder.txtName.setText(call.name);
                holder.txtPhone.setText(call.phone);
            }

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

        public class ViewHolder extends RecyclerView.ViewHolder{

            TextView txtName;
            TextView txtPhone;

            public ViewHolder(@NonNull View itemView) {
                super(itemView);
                txtName = itemView.findViewById(R.id.txtName);
                txtPhone = itemView.findViewById(R.id.txtPhone);
                imgDelete = itemView.findViewById(R.id.imgDelete);

                imgDelete.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        Log.i("CallAdapter","엑스버튼 눌렀음");
                        // 인덱스에 해당하는 데이터를 삭제하면 된다.
                        
                        // 유저가 누른 인덱스를 가져올 수 있는 함수
                        int index = getAdapterPosition();
                        // 인덱스에 해당하는 데이터를 삭제한다
                        callList.remove(index);
                        // 근데 여기까지만 하면 데이터를 삭제하는거지 화면에서 삭제안된다
                        // 데이터가 바뀌었으면, 화면 갱신도 해야한다
                        notifyDataSetChanged();
                    }
                });
            }

        }
}

package com.example.callbook;

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

import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;

import com.example.callbook.adapter.CallAdapter;
import com.example.callbook.model.Call;
import com.google.android.material.snackbar.Snackbar;

import java.util.ArrayList;

public class MainActivity extends AppCompatActivity {

    EditText editName;
    EditText editPhone;
    Button btnSave;

    RecyclerView recyclerView;
    CallAdapter adaptor;
    ArrayList<Call> callList = new ArrayList<>(); // NullPointException

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

        editName = findViewById(R.id.editName);
        editPhone = findViewById(R.id.editPhone);
        btnSave = findViewById(R.id.btnSave);
        recyclerView = findViewById(R.id.recyclerView);

        recyclerView.setHasFixedSize(true);
        recyclerView.setLayoutManager(new LinearLayoutManager(MainActivity.this)); // 가로냐 세로냐 또는 똑같은 이미지 여러개 나오게 할거냐? 등등을 해주는 코드

        btnSave.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                String name = editName.getText().toString().trim();
                String phone = editPhone.getText().toString().trim();
                if(name.isEmpty() || phone.isEmpty()){
                    Snackbar.make(btnSave,"이름과 전화번호는 필수입니다.",Snackbar.LENGTH_SHORT).show();
                    return;
                }
                Call call = new Call();
                // Call call = new Call(name,phone); 관련 생성자 만들면 이렇게 쓸 수 있다
                call.name= name;
                call.phone = phone;

                callList.add(0,call); // index 0을 사용하면 최근 메모가 가장 위에 추가된다
                adaptor.notifyDataSetChanged(); // 그래서 이걸 넣어주면 데이터가변화했다는걸 adaptor에 알려줄 수 있다
                editName.setText("");
                editPhone.setText("");
                // focusablle이라는 기능도 있음
            }
        }); 
        
        adaptor = new CallAdapter(MainActivity.this,callList); // 어댑터 생성
        recyclerView.setAdapter(adaptor);


    }
}

+ 상세 설명 추가