티스토리 뷰

반응형

Stack Overflow에 자주 검색, 등록되는 문제들과 제가 개발 중 찾아 본 문제들 중에서 나중에도 찾아 볼 것 같은 문제들을 정리하고 있습니다.

Stack Overflow에서 가장 먼저 확인하게 되는 가장 높은 점수를 받은 Solution과 현 시점에 도움이 될 수 있는 가장 최근에 업데이트(최소 점수 확보)된 Solution을 각각 정리하였습니다.

 

아래 word cloud를 통해 이번 포스팅의 주요 키워드를 미리 확인하세요.

How to implement Android Pull-to-Refresh

Android 당겨서 새로고침 구현 방법

 문제 내용 

In Android applications such as Twitter (official app), when you encounter a ListView, you can pull it down (and it will bounce back when released) to refresh the content.

Twitter(공식 앱)와 같은 안드로이드 애플리케이션에서 ListView를 발견하면 아래로 끌어내릴 수 있으며(풀리면 다시 되돌아온다) 콘텐츠를 새로 고칠 수 있습니다.

 

I wonder what is the best way, in your opinion, to implement that?

당신의 생각에 그것을 실행하는 가장 좋은 방법이 무엇인지 궁금합니다.

 

Some possibilities I could think of:

제가 생각할 수 있는 몇 가지 가능성:

 

  1. An item on top of the ListView - however I don't think scrolling back to item position 1 (0-based) with animation on the ListView is an easy task.
  2. Another view outside the ListView - but I need to take care of moving the ListView position down when it is pulled, and I'm not sure if we can detect if the drag-touches to the ListView still really scroll the items on the ListView.
리스트뷰 위의 아이템 - 하지만 리스트뷰에서 애니메이션을 사용하여 항목 위치 1(0 기반)로 다시 스크롤하는 것은 쉬운 작업이 아니라고 생각합니다.
리스트뷰 외부의 다른 뷰 - 리스트뷰 위치를 끌어다 놓을 때 아래로 이동해야 하는데 리스트뷰로 끌어다 놓으면 리스트뷰의 항목이 스크롤되는지 여부를 감지할 수 있을지 모르겠습니다.

 

Any recommendations?

추천할 만한 것이 있을까요?

 

P.S. I wonder when the official Twitter app source code is released. It has been mentioned that it will be released, but 6 months has passed and we haven't heard about it since then.

추신: 공식 트위터 앱 소스 코드가 언제 공개되는지 궁금합니다. 출시한다고 했는데 6개월이 지났는데 그 이후로 소식이 없네요.

 

 

 

 높은 점수를 받은 Solution 

Finally, Google released an official version of the pull-to-refresh library!

마침내, 구글은 당겨서 새로고침 라이브러리의 공식 버전을 출시했습니다!

 

It is called SwipeRefreshLayout, inside the support library, and the documentation is here:

서포트 라이브러리 내부의 SweepRefreshLayout이라고 하며 설명서는 다음과 같습니다.

 

  1. Add SwipeRefreshLayout as a parent of view which will be treated as a pull to refresh the layout. (I took ListView as an example, it can be any View like LinearLayout, ScrollView etc.)
  2. <androidx.swiperefreshlayout.widget.SwipeRefreshLayout xmlns:android="http://schemas.android.com/apk/res/android" android:id="@+id/pullToRefresh" android:layout_width="match_parent" android:layout_height="match_parent"> <ListView android:id="@+id/listView" android:layout_width="match_parent" android:layout_height="match_parent"/> </androidx.swiperefreshlayout.widget.SwipeRefreshLayout>
  3. Add a listener to your class
  4. protected void onCreate(Bundle savedInstanceState) { final SwipeRefreshLayout pullToRefresh = findViewById(R.id.pullToRefresh); pullToRefresh.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() { @Override public void onRefresh() { refreshData(); // your code pullToRefresh.setRefreshing(false); } }); }
1. SwipeRefreshLayout을 당겨서 새로고침 처리할 뷰의 부모로 추가합니다. (저는 ListView를 예로 들었습니다. LinearLayout, ScrollView 등과 같은 모든 뷰가 될 수 있습니다.)
2. 코드..
3. 리스너를 당신의 클래스에 추가하세요.
4. 코드..

 

You can also call pullToRefresh.setRefreshing(true/false); as per your requirement.

당신의 요구 사항에 따라 pullToRefresh.setRefresh(true/false)를 호출할 수도 있습니다. (당겨서 새로고침 on/off 가능)

 

UPDATE

수정

 

Android support libraries have been deprecated and have been replaced by AndroidX. The link to the new library can be found here.

안드로이드 서포트 라이브러리는 더 이상 사용되지 않으며 안드로이드X로 대체되었습니다. 새 라이브러리에 대한 링크는 여기에서 찾을 수 있습니다.

 

Also, you need to add the following dependency to your project:

또한 프로젝트에 다음과 같은 종속성을 추가해야 합니다.
implementation 'androidx.swiperefreshlayout:swiperefreshlayout:1.1.0'

 

OR

또는

 

You can go to Refactor>>Migrate to AndroidX and Android Studio will handle the dependencies for you.

Refactor>>AndroidX로 마이그레이션하면 Android Studio에서 종속성을 처리할 수 있습니다.

 

 

 

 가장 최근 달린 Solution 

The easiest way i think is as provided by the android support library:

제가 생각하는 가장 쉬운 방법은 안드로이드 서포트 라이브러리에서 제공하는 것이다.

 

android.support.v4.widget.SwipeRefreshLayout;

android.support.v4.widget.SwipeRefreshLayout;

 

once that is imported then you can have your layout defined as follows:

이를 가져오면 레이아웃을 다음과 같이 정의할 수 있습니다.
  <android.support.v4.widget.SwipeRefreshLayout
        android:id="@+id/refresh"
        android:layout_height="match_parent"
        android:layout_width="match_parent">
    <android.support.v7.widget.RecyclerView
        xmlns:recycler_view="http://schemas.android.com/apk/res-auto"
        android:id="@android:id/list"
        android:theme="@style/Theme.AppCompat.Light"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:background="@color/button_material_light"
        >

    </android.support.v7.widget.RecyclerView>
</android.support.v4.widget.SwipeRefreshLayout>

 

I assume that you use recycler view instead of listview. However, listview still works so you just need to replace recyclerview with listview and update the references in the java code (Fragment).

listview 대신 recycler view를 사용한다고 가정합니다. 그러나 listview는 여전히 작동하므로 recyclerview를 listview로 바꾸고 Java 코드(Fragment)의 참조를 수정하기만 하면 됩니다.

 

In your activity fragment, you first implement the interface, SwipeRefreshLayout.OnRefreshListener: i,e

당신의 액티비티 플래그먼트에서 먼저 인터페이스인 OnRefreshListener를 구현합니다.
public class MySwipeFragment extends Fragment implements SwipeRefreshLayout.OnRefreshListener{
private SwipeRefreshLayout swipeRefreshLayout;

@Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_item, container, false);
        swipeRefreshLayout = (SwipeRefreshLayout) view.findViewById(R.id.refresh);
        swipeRefreshLayout.setOnRefreshListener(this);
}


 @Override
  public void onRefresh(){
     swipeRefreshLayout.setRefreshing(true);
     refreshList();
  }
  refreshList(){
    //do processing to get new data and set your listview's adapter, maybe  reinitialise the loaders you may be using or so
   //when your data has finished loading, cset the refresh state of the view to false
   swipeRefreshLayout.setRefreshing(false);

   }
}

 

Hope this helps the masses

이것이 대중에게 도움이 되기를 바랍니다.

 

 

 

출처 : https://stackoverflow.com/questions/4583484/how-to-implement-android-pull-to-refresh

반응형
댓글
공지사항
최근에 올라온 글