본문 바로가기
개발/Android

안드로이드 Intent를 이용하여 선택한 Recyclerview 화면으로 포커싱하는 방법

by 남트로 2023. 4. 21.

오늘은 Intent를 사용하여 선택한  RecyclerView 화면으로 포커싱 하는 방법에 대해서 알아볼 것이다.

 

개발하는중 동일한 데이터를 가진 RecyclerView를 다른 액티비티에 두개 만든 뒤, 하나는 사진만 나오는 RecyclerView 나머지 하나는 사진과 제목 글까지 나오는 RecyclerView 이렇게 두개로 만들었다.

 

그때 사진만 나오는 RecyclerView의 데이터를 클릭했을 때 사진과 제목 글까지 나오는 RecyclerView로 이동한 뒤 해당 사진이 들어있는 글로 넘어가게 하고 싶어서 알아보았다.

 

 

하는 방법은 간단하였다.

 

Intent를 이용하여 position 값만 넘겨주면 된다.



먼저 넘어가기 전 RecyclerView에 Intent로 position 값을 넣어주었다.

 

FirstActivity.java

Adapter.setOnItemClickListener(new Adapter.OnItemClickListener() {
            @Override
            public void onItemClick(View v, int position) {

                AlertDialog.Builder builder = new AlertDialog.Builder(getContext());

                        Intent intent = new Intent(getActivity(), ㄴSecondActivity.class);
                        intent.putExtra("position", position);
                        startActivity(intent);

onItemClickListener를 통해서 position 값을 이용한 뒤 Intent로 다음 액티비티로 넘어갈 때 position 값도 함께 넘겨주는 것이다.

 

 

SecondActivity.java

 Intent intent = getIntent();
        int position = intent.getIntExtra("position", 0);
        new Handler().postDelayed(new Runnable() {
            @Override
            public void run() {
                recyclerView.scrollToPosition(position);
            }
        }, 100);

그 다음에 넘어가는 액티비티에서 onCreate 부분에 intent.getintExtra로 position 값을 받아오고 recyclerView.scrollToPosition(position)을 하면 받아온 position 값의 스크롤로 이동하게 된다.

이때 Handler를 사용해주어야 하는데 그냥 recyclerView를 사용하면 이상하게도 인식을 하지 못한다. 그래서 Handler를 통해 딜레이를 주어야 정상적으로 인식하고 클릭한 데이터의 화면으로 정상적으로 이동하는 것을 볼 수 있다.

댓글