๊ด€๋ฆฌ ๋ฉ”๋‰ด

ruriruriya

[Android] ์•ˆ๋“œ๋กœ์ด๋“œ - RecyclerView Adapter์—์„œ ์ƒˆ๋กœ์šด ์•กํ‹ฐ๋น„ํ‹ฐ ์‹คํ–‰ํ•˜๋Š” ๋ฐฉ๋ฒ•(Context) ๋ณธ๋ฌธ

๐Ÿค–Android/Java

[Android] ์•ˆ๋“œ๋กœ์ด๋“œ - RecyclerView Adapter์—์„œ ์ƒˆ๋กœ์šด ์•กํ‹ฐ๋น„ํ‹ฐ ์‹คํ–‰ํ•˜๋Š” ๋ฐฉ๋ฒ•(Context)

๋ฃจ๋ฆฌ์•ผใ…‘ 2023. 12. 29. 09:29
๋ฐ˜์‘ํ˜•

์ฝ˜ํ…์ŠคํŠธ(Context)๋Š” ์•ˆ๋“œ๋กœ์ด๋“œ ์• ํ”Œ๋ฆฌ์ผ€์ด์…˜์˜ ์ „์—ญ ์ •๋ณด์— ์ ‘๊ทผํ•  ์ˆ˜ ์žˆ๋Š” ์ธํ„ฐํŽ˜์ด์Šค์ด๋‹ค.
์•ˆ๋“œ๋กœ์ด๋“œ ์• ํ”Œ๋ฆฌ์ผ€์ด์…˜์€ ์•กํ‹ฐ๋น„ํ‹ฐ(Activity), ์„œ๋น„์Šค(Service), ์–ดํ”Œ๋ฆฌ์ผ€์ด์…˜(Application) ๋“ฑ์˜ ์ปดํฌ๋„ŒํŠธ๋กœ ๊ตฌ์„ฑ๋œ๋‹ค.
์ด๋Ÿฌํ•œ ์ปดํฌ๋„ŒํŠธ๋“ค์€ ๋ชจ๋‘ ์ฝ˜ํ…์ŠคํŠธ๋ฅผ ๊ฐ€์ง€๊ณ  ์žˆ์œผ๋ฉฐ, ์ฝ˜ํ…์ŠคํŠธ๋ฅผ ํ†ตํ•ด ๋ฆฌ์†Œ์Šค, ํด๋ž˜์Šค, ์•ฑ ํ™˜๊ฒฝ ์ •๋ณด ๋“ฑ์— ์ ‘๊ทผํ•  ์ˆ˜ ์žˆ๋‹ค.

์–ด๋Œ‘ํ„ฐ(Adapter) ํด๋ž˜์Šค๋Š” ์ปจํ…์ŠคํŠธ์— ์ง์ ‘ ์ ‘๊ทผํ•  ์ˆ˜ ์—†์ง€๋งŒ, ์ƒ์„ฑ์ž๋ฅผ ํ†ตํ•ด ์ฝ˜ํ…์ŠคํŠธ๋ฅผ ์ „๋‹ฌ๋ฐ›์„ ์ˆ˜ ์žˆ๋‹ค.
์ฃผ๋กœ ์–ด๋Œ‘ํ„ฐ๋Š” ์•กํ‹ฐ๋น„ํ‹ฐ(Activity)๋‚˜ ์ปจํ…์ŠคํŠธ๋ฅผ ํ•„์š”๋กœ ํ•˜๋Š” ๋‹ค๋ฅธ ์•ˆ๋“œ๋กœ์ด๋“œ ์ปดํฌ๋„ŒํŠธ๋กœ๋ถ€ํ„ฐ ์ƒ์„ฑ์ž๋ฅผ ํ†ตํ•ด ์ฝ˜ํ…์ŠคํŠธ๋ฅผ ์ „๋‹ฌ๋ฐ›์•„ ์‚ฌ์šฉํ•œ๋‹ค.

 

1. Adapter ํด๋ž˜์Šค ๋‚ด ๋ฉค๋ฒ„๋ณ€์ˆ˜

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

    Context context;

    ArrayList<Post> postArrayList;
}

 

2. onCreateViewHolder ์˜ค๋ฒ„๋ผ์ด๋”ฉ ํ•จ์ˆ˜ ์ž‘์„ฑ

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

 

3. MainActivity  ํ™”๋ฉด ํ‘œ์‹œ ๋ถ€๋ถ„ recyclerview adapter

//ํ™”๋ฉด์— ํ‘œ์‹œ.
adapter = new PostAdapter(MainActivity.this, postArrayList);
recyclerView.setAdapter(adapter);

 

4. Adapter ํด๋ž˜์Šค์— ์ƒ์„ฑ์ž ์ƒ์„ฑ

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

    Context context;

    ArrayList<Post> postArrayList;
    
    public PostAdapter(Context context, ArrayList<Post> postArrayList){
        this.context = context;
        this.postArrayList = postArrayList;
    }
}
๋ฐ˜์‘ํ˜•