본문 바로가기
안드로이드/개발자 일상

안드로이드 Retrofit2+RecyclerView 1-2 (추가 밀어서 삭제,편집 )

by 차누감 2020. 4. 6.
반응형

안드로이드 Retrofit2+RecyclerView 1-1에서는 영화진흥위원회에서 영화정보를 리스트형식으로 보이게 했습니다.

2020/03/22 - [안드로이드/개발자 일상] - 안드로이드 Retrofit2+RecyclerView 1-1(영화진흥위원회 오픈 API 이용)

(링크 참조 바랍니다.)

 

위 예제에서 추가하여 이제 밀어서 삭제,편집을 선택 할 수있도록 해보겠습니다.

추가할 것들

interface MyButtonClickListener 

ItemTouchHelper.SimpleCallback를 상속 받은 abstract class MySwipeHelper

그리고 MainActivity에 사용하면 됩니다. 

 

<실행 화면> 영화 목록을 옆으로 드래그 했을때, 선택을 할 수 있습니다.


interface를 만들어 줍니다.

MyButtonClickListener.java

1
2
3
4
5
6
package com.example.ex_retrofit_recyclerview;
 
public interface MyButtonClickListener {
    void onClick(int pos);
}
 
 

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

MySwipeHelper.java

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
package com.example.ex_retrofit_recyclerview;
 
import android.content.Context;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
 
import androidx.annotation.NonNull;
 
 
 
public abstract class MySwipeHelper extends ItemTouchHelper.SimpleCallback {
 
    int buttonWidth;
    private RecyclerView recyclerView;
    private List<MyButton> buttonList;
    private GestureDetector gestureDetector;
    private int swipePosition=-1;
    private float swipeThreshold = 0.5f;
    private Map<Integer,List<MyButton>> buttonBuffer;
    private Queue<Integer> removerQueue;
    private  GestureDetector.SimpleOnGestureListener gestureListener= new GestureDetector.SimpleOnGestureListener(){
 
        @Override
        public boolean onSingleTapUp(MotionEvent e) {
            for(MyButton button:buttonList){
                if(button.onClick(e.getX(),e.getY()))
                    break;
            }
            return super.onSingleTapUp(e);
        }
    };
 
    private View.OnTouchListener onTouchListener= new View.OnTouchListener() {
        @Override
        public boolean onTouch(View v, MotionEvent motionEvent) {
            if(swipePosition<0return false;
            Point point =new Point((int)motionEvent.getRawX(),(int)motionEvent.getRawY());
 
            RecyclerView.ViewHolder swipeViewHolder = recyclerView.findViewHolderForAdapterPosition(swipePosition);
            View swipedItem=swipeViewHolder.itemView;
            Rect rect= new Rect();
            swipedItem.getGlobalVisibleRect(rect);
 
            if(motionEvent.getAction() == MotionEvent.ACTION_DOWN ||
               motionEvent.getAction() == MotionEvent.ACTION_UP ||
               motionEvent.getAction() == MotionEvent.ACTION_MOVE){
 
                if (rect.top<point.y && rect.bottom> point.y) gestureDetector.onTouchEvent(motionEvent);
                else {
                    removerQueue.add(swipePosition);
                    swipePosition = -1;
                    recoverSwipedItem();
                }
            }
            return false;
        }
    };
 
    protected  synchronized void recoverSwipedItem(){
        while (!removerQueue.isEmpty()){
            int pos=removerQueue.poll();
            if(pos> -1) recyclerView.getAdapter().notifyItemChanged(pos);
        }
    }
 
 
    public MySwipeHelper(Context context, RecyclerView recyclerView, int buttonWidth) {
        super(0,ItemTouchHelper.LEFT);
        this.recyclerView= recyclerView;
        this.buttonList= new ArrayList<>();
        this.gestureDetector= new GestureDetector(context,gestureListener);
        this.recyclerView.setOnTouchListener(onTouchListener);
        this.buttonBuffer= new HashMap<>();
        this.buttonWidth= buttonWidth;
 
        removerQueue= new LinkedList<Integer>(){
            @Override
            public boolean add(Integer integer) {
               if(contains(integer)) return false;
               else return super.add(integer);
            }
        };
            
        attachSwipe();
        
    }// MySwipeHelper*()..
 
    private void attachSwipe() {
        ItemTouchHelper itemTouchHelper=new ItemTouchHelper(this);
        itemTouchHelper.attachToRecyclerView(recyclerView);
    }
 
    public class MyButton{
        private String text;
        private int imageResId,textSize, color,pos;
        private RectF clickRegion;
        private MyButtonClickListener listener;
        private Context context;
        private Resources resources;
 
        public MyButton(Context context, String text,  int textSize,int imageResId, int color, MyButtonClickListener listener) {
            this.text = text;
            this.imageResId = imageResId;
            this.textSize = textSize;
            this.color = color;
 
            this.listener = listener;
            this.context = context;
            resources= context.getResources();
        }// MyButton()..
 
        public boolean onClick(float x, float y){
            if(clickRegion != null && clickRegion.contains(x,y) ){
               listener.onClick(pos);
               return true;
            }
            return false;
        }// onClick()..
 
        public void onDraw(Canvas c, RectF rectF, int pos){
            Paint p = new Paint();
            p.setColor(color);
            c.drawRect(rectF,p);
            //text
            p.setColor(Color.WHITE);
            p.setTextSize(textSize);
 
            Rect r = new Rect();
            float cHeight= rectF.height();
            float cWidth= rectF.width();
            p.setTextAlign(Paint.Align.LEFT);
            p.getTextBounds(text, 0,text.length(),r);
            float x=0, y=0;
            if(imageResId == 0){
                x=cWidth/2f-r.width()/2f -r.left;
                y=cHeight/2f + r.height()/2f -r.bottom;
                c.drawText(text, rectF.left+x,rectF.top+y,p);
            }else{
                Drawable d = ContextCompat.getDrawable(context,imageResId);
                Bitmap bitmap= drawableToBitmap(d);
                c.drawBitmap(bitmap,(rectF.left+rectF.right)/2,(rectF.top+rectF.bottom)/2,p);
            }
            clickRegion= rectF;
            this.pos=pos;
        }
 
    }// MyButton class..
 
    protected  Bitmap drawableToBitmap(Drawable d){
        if(d instanceof BitmapDrawable) return ((BitmapDrawable)d).getBitmap();
        Bitmap  bitmap = Bitmap.createBitmap(d.getIntrinsicWidth(),d.getIntrinsicHeight(), Bitmap.Config.ARGB_8888);
        Canvas canvas= new Canvas(bitmap);
        d.setBounds(0,0,canvas.getWidth(),canvas.getHeight());
        d.draw(canvas);
        return bitmap;
    }
 
    @Override
    public boolean onMove(@NonNull RecyclerView recyclerView, @NonNull RecyclerView.ViewHolder viewHolder, @NonNull RecyclerView.ViewHolder target) {
        return false;
    }
 
    @Override
    public void onSwiped(@NonNull RecyclerView.ViewHolder viewHolder, int direction) {
        int pos=viewHolder.getAdapterPosition();
        if(swipePosition != pos) removerQueue.add(swipePosition);
        swipePosition=pos;
        if(buttonBuffer.containsKey(swipePosition)) buttonList = buttonBuffer.get(swipePosition);
        else buttonList.clear();
        buttonBuffer.clear();
        swipeThreshold= 0.5f*buttonList.size()*buttonWidth;
        recoverSwipedItem();
    }
 
    public float getSwipeThreshold(RecyclerView.ViewHolder viewHolder) {
        return swipeThreshold;
    }
 
    @Override
    public float getSwipeEscapeVelocity(float defaultValue) {
        return 0.1f*defaultValue;
    }
 
    @Override
    public float getSwipeVelocityThreshold(float defaultValue) {
        return 5.0f*defaultValue;
    }
 
    @Override
    public void onChildDraw(@NonNull Canvas c, @NonNull RecyclerView recyclerView, @NonNull RecyclerView.ViewHolder viewHolder, float dX, float dY, int actionState, boolean isCurrentlyActive) {
       int pos= viewHolder.getAdapterPosition();
       float translationX =dX;
       View itemView= viewHolder.itemView;
       if (pos<0){
           swipePosition = pos;
           return;
       }
       if (actionState == ItemTouchHelper.ACTION_STATE_SWIPE){
           if(dX<0){
               List<MyButton> buffer= new ArrayList<>();
               if(!buttonBuffer.containsKey(pos)){
                   instantiatrMyButton(viewHolder,buffer);
                   buttonBuffer.put(pos,buffer);
               }else{
                   buffer = buttonBuffer.get(pos);
               }
               translationX=dX*buffer.size()*buttonWidth / itemView.getWidth();
               drawButton(c,itemView,buffer,pos,translationX);
           }
       }
       super.onChildDraw(c,recyclerView,viewHolder,translationX,dY,actionState,isCurrentlyActive);
    }
 
    private void drawButton(Canvas c, View itemView, List<MyButton> buffer, int pos, float translationX) {
        float right = itemView.getRight();
        float dButtonWidth = -1*translationX / buffer.size();
        for(MyButton button:buffer){
            float left= right - dButtonWidth;
            right=left;
        }
    }
 
    public abstract void instantiatrMyButton(RecyclerView.ViewHolder viewHolder, List<MyButton> buffer) ;
}// MySwipeHelper class..
 
 

아이콘을 미리 추가 합니다.

이제 MainActivity에서 사용만 하면 됩니다. 

( 기존 코드에서 63번줄 ~ 93번줄만 추가했습니다. )

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
package com.example.ex_retrofit_recyclerview;
 
 
 
 
import retrofit2.Callback;
import retrofit2.Response;
import retrofit2.Retrofit;
 
public class MainActivity extends AppCompatActivity {
 
    private RecyclerView recyclerView;
    private RecyclerView.Adapter mAdapter;
 
    String baseUrl = "http://www.kobis.or.kr";
    String API_KEY = "영화진흥위원회에서 발급 받은 Key를 넣어주세요";
 
    Retrofit retrofit;
 
    Map<String,Object> boxOfficeResult;
    ArrayList<Map<String, Object>> jsonList;
 
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
 
        recyclerView=findViewById(R.id.rv_recyclerview);
 
        //Retrofit 객체생성
        retrofit = new Retrofit.Builder()
                .baseUrl(baseUrl)
                .addConverterFactory(GsonConverterFactory.create())
                .build();
        RetrofitInterface retrofitInterface= retrofit.create(RetrofitInterface.class);
 
        retrofitInterface.getBoxOffice(API_KEY,"20200319").enqueue(new Callback<Map<String, Object>>() {
            @Override
            public void onResponse(Call<Map<String, Object>> call, Response<Map<String, Object>> response) {
 
               boxOfficeResult= (Map<String, Object>response.body().get("boxOfficeResult");
               jsonList = (ArrayList) boxOfficeResult.get("dailyBoxOfficeList");
                mAdapter=new MyAdapter(jsonList);
            }
            @Override
            public void onFailure(Call<Map<String, Object>> call, Throwable t) {
 
            }
        });
 
        MySwipeHelper swipeHelper= new MySwipeHelper(MainActivity.this,recyclerView,300) {
            @Override
            public void instantiatrMyButton(RecyclerView.ViewHolder viewHolder, List<MySwipeHelper.MyButton> buffer) {
                buffer.add(new MyButton(MainActivity.this,
                        "Delete",
                        30,
                        R.drawable.ic_delete_black_24dp,
                        Color.parseColor("#FF3C30"),
                        new MyButtonClickListener() {
                            @Override
                            public void onClick(int pos) {
                                Toast.makeText(MainActivity.this"Delete click", Toast.LENGTH_SHORT).show();
                                Log.d("TAG",viewHolder.getAdapterPosition()+"");
                                jsonList.remove(viewHolder.getAdapterPosition());                // 해당 항목 삭제
                                mAdapter.notifyItemRemoved(viewHolder.getAdapterPosition());    // Adapter에 알려주기.
                            }
                        }));
                buffer.add(new MyButton(MainActivity.this,
                        "Update",
                        30,
                        R.drawable.ic_edit_white_24dp,
                        Color.parseColor("#03DAC5"),
                        new MyButtonClickListener() {
                            @Override
                            public void onClick(int pos) {
                                Toast.makeText(MainActivity.this"edit click", Toast.LENGTH_SHORT).show();
                                //TODO: 편집할 코드
                            }
                        }));
            }
        };// swipeHelper
 
    }// onCreate()..
 
    public void click_btn(View view) {
 
        recyclerView.setAdapter(mAdapter);
    }
 
}// MainActivity class..
 
 

<실행 화면>

반응형

댓글