programing

Android Pull-to-Refresh를 구현하는 방법

subpage 2023. 7. 8. 10:54
반응형

Android Pull-to-Refresh를 구현하는 방법

Twitter(공식 앱)와 같은 Android 응용 프로그램에서 ListView를 사용하면 ListView를 아래로 끌어내릴 수 있으며(ListView가 해제되면 다시 튀어나올 것입니다) 콘텐츠를 새로 고칠 수 있습니다.

저는 그것을 실행하기 위한 가장 좋은 방법이 무엇이라고 생각하는지 궁금합니다.

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

  1. 목록 보기 위에 있는 항목 - 그러나 목록 보기에서 애니메이션으로 항목 위치 1(0 기반)로 다시 스크롤하는 것은 쉬운 작업이 아니라고 생각합니다.
  2. ListView 외부의 다른 보기 - 그러나 ListView가 당겨질 때 ListView 위치를 아래로 이동해야 합니다. ListView로 드래그 터치하면 ListView의 항목이 실제로 스크롤되는지 여부를 감지할 수 있을지 모르겠습니다.

추천할 만한 것이 있습니까?

추신. 공식 트위터 앱 소스 코드는 언제 공개되는지 궁금합니다.출시될 것이라는 얘기가 나왔지만 6개월이 지났고 그 이후로 소식이 없습니다.

마침내, 구글은 풀 투 리프레시 라이브러리의 공식 버전을 출시했습니다!

은 라고합니다라고 .SwipeRefreshLayout설명서는 다음과 같습니다.

  1. 더하다SwipeRefreshLayout레이아웃을 새로 고치기 위한 풀로 처리되는 뷰의 상위 항목입니다.(내가 가져갔어요ListView예를 들어, 그것은 아무 것이나 될 수 있습니다.View맘에 들다LinearLayout,ScrollView아래)

     <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>
    
  2. 클래스에 수신기 추가

     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);
             }
         });
     }
    

또한 전화할 수 있습니다.pullToRefresh.setRefreshing(true/false);귀하의 요구에 따라

갱신하다

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

또한 다음과 같은 종속성을 프로젝트에 추가해야 합니다.

implementation 'androidx.swiperefreshlayout:swiperefreshlayout:1.1.0'

OR

Refactor >>Migrate to Android X로 이동하면 Android Studio에서 종속성을 처리합니다.

구성 요소를 새로 고치기 위해 풀을 구현하려고 시도했지만 아직 완전하지는 않지만 구현 가능성을 보여줍니다. https://github.com/johannilsson/android-pulltorefresh .

는 주요논는다같구다니현됩이로 구현됩니다.PullToRefreshListView그것은 확장되는ListView. 내부적으로 다음을 사용하여 머리글 보기의 스크롤을 제어합니다. smoothScrollBy (API 레벨 8). 이제 위젯이 1.5 이상 지원으로 업데이트되었습니다. 단, 1.5 지원은 README를 참조하십시오.

레이아웃에서 이렇게 추가하면 됩니다.

<com.markupartist.android.widget.PullToRefreshListView
    android:id="@+id/android:list"
    android:layout_height="fill_parent"
    android:layout_width="fill_parent"
    />

저는 Android용으로 강력하고 오픈 소스, 사용하기 쉽고 사용자 정의가 뛰어난 PullToRefresh 라이브러리도 구현했습니다.프로젝트 페이지의 설명서에 설명된 대로 ListView를 PullToRefreshListView로 바꿀 수 있습니다.

https://github.com/erikwt/PullToRefresh-ListView

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

안드로이드의support.v4.vmdk.새로 고침 레이아웃을 스와이프합니다.

가져온 레이아웃을 다음과 같이 정의할 수 있습니다.

  <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>

목록 보기 대신 재활용 보기를 사용하는 것 같습니다.그러나 목록 보기는 여전히 작동하므로 재활용 보기를 목록 보기로 바꾸고 Java 코드(Fragment)의 참조를 업데이트하기만 하면 됩니다.

당의활단편서에동다, 당은먼인를구스현니합이터페저신신▁the를 합니다.SwipeRefreshLayout.OnRefreshListener,e

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);

   }
}

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

이 링크에서, 당신은 유명한 포크를 찾을 수 있습니다.PullToRefresh와 같은 새로운 뷰PullTorRefreshWebView또는PullToRefreshGridView 는를추할가능을 .PullToRefresh목록의 맨 아래 가장자리에

https://github.com/chrisbanes/Android-PullToRefresh

좋은 점은 4 4.1 )에서 완벽하게 작동한다는 입니다.PullToRefresh않음)

Android Pull-to-Refresh를 구현하려면 이 코드를 사용해 보십시오.

<android.support.v4.widget.SwipeRefreshLayout
        android:id="@+id/pullToRefresh"
        android:layout_width="match_parent"
        android:layout_height="wrap_content">

    <ListView
        android:id="@+id/lv"
        android:layout_width="match_parent"
        android:layout_height="match_parent" >
    </ListView>

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

활동 클래스:

ListView lv = (ListView) findViewById(R.id.lv);
SwipeRefreshLayout pullToRefresh = (SwipeRefreshLayout) findViewById(R.id.pullToRefresh);


lv.setAdapter(mAdapter);

pullToRefresh.setOnRefreshListener(new OnRefreshListener() {

        @Override
        public void onRefresh() {
            // TODO Auto-generated method stub

            refreshContent();

        }
    });



private void refreshContent(){ 

     new Handler().postDelayed(new Runnable() {
            @Override public void run() {
                pullToRefresh.setRefreshing(false);
            }
        }, 5000);

 }

나는 이것을 하는 매우 쉬운 방법을 가지고 있지만 이제 그것이 완벽한 방법임을 확신합니다. 내 코드 PullDownListView.java.

package com.myproject.widgets;

import android.content.Context;
import android.util.AttributeSet;
import android.view.MotionEvent;
import android.widget.AbsListView;
import android.widget.AbsListView.OnScrollListener;
import android.widget.ListView;

/**
 * @author Pushpan
 * @date Nov 27, 2012
 **/
public class PullDownListView extends ListView implements OnScrollListener {

    private ListViewTouchEventListener mTouchListener;
    private boolean pulledDown;

    public PullDownListView(Context context) {
        super(context);
        init();
    }

    public PullDownListView(Context context, AttributeSet attrs) {
        super(context, attrs);
        init();
    }

    public PullDownListView(Context context, AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);
        init();
    }

    private void init() {
        setOnScrollListener(this);
    }

    private float lastY;

    @Override
    public boolean dispatchTouchEvent(MotionEvent ev) {
        if (ev.getAction() == MotionEvent.ACTION_DOWN) {
            lastY = ev.getRawY();
        } else if (ev.getAction() == MotionEvent.ACTION_MOVE) {
            float newY = ev.getRawY();
            setPulledDown((newY - lastY) > 0);
            postDelayed(new Runnable() {
                @Override
                public void run() {
                    if (isPulledDown()) {
                        if (mTouchListener != null) {
                            mTouchListener.onListViewPulledDown();
                            setPulledDown(false);
                        }
                    }
                }
            }, 400);
            lastY = newY;
        } else if (ev.getAction() == MotionEvent.ACTION_UP) {
            lastY = 0;
        }
        return super.dispatchTouchEvent(ev);
    }

    @Override
    public void onScroll(AbsListView view, int firstVisibleItem,
            int visibleItemCount, int totalItemCount) {
        setPulledDown(false);
    }

    @Override
    public void onScrollStateChanged(AbsListView view, int scrollState) {
    }

    public interface ListViewTouchEventListener {
        public void onListViewPulledDown();
    }

    public void setListViewTouchListener(
            ListViewTouchEventListener touchListener) {
        this.mTouchListener = touchListener;
    }

    public ListViewTouchEventListener getListViewTouchListener() {
        return mTouchListener;
    }

    public boolean isPulledDown() {
        return pulledDown;
    }

    public void setPulledDown(boolean pulledDown) {
        this.pulledDown = pulledDown;
    }
}

ListView를 구현하기만 하면 됩니다.이 목록 보기를 사용하고 수신기를 설정할 활동에서 이벤트 수신기를 누릅니다.

PullDownListView Activity에 구현했습니다.

package com.myproject.activities;

import android.app.Activity;
import android.os.Bundle;

/**
 * @author Pushpan
 *
 */
public class PullDownListViewActivity extends Activity implements ListViewTouchEventListener {

    private PullDownListView listView;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        listView = new PullDownListView(this);
        setContentView(listView);
        listView.setListViewTouchListener(this);

        //setItems in listview
    }

    public void onListViewPulledDown(){
        Log.("PullDownListViewActivity", "ListView pulled down");
    }
}

저한테는 효과가 있어요 :)

아무도 Google Now나 Gmail 응용 프로그램처럼 수행 표시줄 위에 표시되는 새로운 유형의 "Pull to Refresh"에 대해 언급하지 않았습니다.

정확히 동일하게 작동하는 ActionBar-PullToRefresh 라이브러리가 있습니다.

Android 및 WP에서 구현할 때 해결해야 할 UX 문제가 있습니다.

"설계자/개발자가 iOS 앱과 같은 방식으로 풀 투 리프레시를 구현해서는 안 되는 이유를 보여주는 훌륭한 지표는 iOS에서 사용하는 동안 Google과 그 팀이 안드로이드에서 풀 투 리프레시를 사용하지 않는다는 것입니다."

https://plus.google.com/109453683460749241197/posts/eqYxXR8L4eb

프로그램이 Android에 강제로 장착된 iPhone 프로그램처럼 보이지 않도록 하려면 보다 기본적인 모양과 느낌, 진저브레드와 유사한 작업을 수행하십시오.

alt text

여기에 구성 요소를 새로 고치기 위한 풀을 작성했습니다. https://github.com/guillep/PullToRefresh 목록에 항목이 없으면 이벤트가 작동하며 >=1.6 안드로이드 폰에서 테스트했습니다.

어떠한 제안이나 개선도 감사합니다 :)

제 생각에 최고의 도서관은 https://github.com/chrisbanes/Android-PullToRefresh 입니다.

작업 대상:

ListView
ExpandableListView
GridView
WebView
ScrollView
HorizontalScrollView
ViewPager

먼저 안드로이드에서 Pull to refresh 레이아웃이 무엇인지 알아야 합니다. 안드로이드에서 Pull to refresh를 swip-to-refresh로 호출할 수 있습니다. 화면을 위에서 아래로 스와이프하면 setOnRefreshListener를 기반으로 몇 가지 작업을 수행합니다.

다음은 안드로이드 풀을 새로 고치는 방법을 설명하는 튜토리얼입니다.이것이 도움이 되길 바랍니다.

최신 롤리팝 Pull-To Refresh를 받으려면:

  1. 최신 Rollipop SDK 및 Extras/Android 지원 라이브러리 다운로드
  2. 프로젝트의 빌드 대상을 Android 5.0으로 설정합니다(그렇지 않으면 지원 패키지에 리소스 오류가 발생할 수 있음).
  3. libs/Android-support-v4.jar를 21번째 버전으로 업데이트합니다.
  4. 사용하다android.support.v4.widget.SwipeRefreshLayout플러스android.support.v4.widget.SwipeRefreshLayout.OnRefreshListener

자세한 가이드는 http://antonioleiva.com/swiperefreshlayout/ 에서 확인할 수 있습니다.

ListView에 대해서도 읽어보기를 권장합니다.canChildScrollUp()댓글에 ;)

얄란티스의 매우 흥미로운 투 리프레시.iOS용 GIF, 하지만 확인할 수 있습니다 :)

<com.yalantis.pulltorefresh.library.PullToRefreshView
android:id="@+id/pull_to_refresh"
android:layout_width="match_parent"
android:layout_height="match_parent">
<ListView
    android:id="@+id/list_view"
    android:divider="@null"
    android:dividerHeight="0dp"
    android:layout_width="match_parent"
    android:layout_height="match_parent" />

RecyclerView에 풀 투 리프레시 기능을 구현하려는 사용자는 Android에서 Pull To Refresh를 구현하는 방법에 대한 간단한 튜토리얼을 따르십시오.

가져올 라이브러리

implementation 'androidx.appcompat:appcompat:1.2.0'
implementation 'androidx.gridlayout:gridlayout:1.0.0'

XML 코드

<androidx.swiperefreshlayout.widget.SwipeRefreshLayout
    android:id="@+id/swipe_layout"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <androidx.recyclerview.widget.RecyclerView
        android:id="@+id/recycler_view"
        android:layout_width="match_parent"
        android:layout_height="match_parent"/>

</androidx.swiperefreshlayout.widget.SwipeRefreshLayout>

활동 JAVA 코드

import androidx.appcompat.app.AppCompatActivity;
import androidx.swiperefreshlayout.widget.SwipeRefreshLayout;
import android.os.Bundle;
import android.os.Handler;

public class MainActivity extends AppCompatActivity {

private SwipeRefreshLayout swipeRefreshLayout;

...

@Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
       
        ...
        swipeRefreshLayout = findViewById(R.id.swipe_layout);
        initializeRefreshListener();
}

    void initializeRefreshListener() {

        swipeRefreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {
                // This method gets called when user pull for refresh,
                // You can make your API call here,
                // We are using adding a delay for the moment
                final Handler handler = new Handler();
                handler.postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        if(swipeRefreshLayout.isRefreshing()) {
                            swipeRefreshLayout.setRefreshing(false);
                        }
                    }
                }, 3000);
            }
        });
    }

풀을 사용하여 웹 보기나 다른 곳에서 새로 고치려면 이 코드를 프로젝트에 복사하여 붙여넣기만 하면 됩니다.

XML 원본 코드:

   <androidx.swiperefreshlayout.widget.SwipeRefreshLayout
        xmlns:android="http://schemas.android.com/apk/res/android"
        android:id="@+id/swiperefresh"
        android:layout_width="match_parent"
        android:layout_height="match_parent">
    <WebView
        android:id="@+id/WebView"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_alignParentLeft="true"
        android:layout_alignParentRight="true">
    </WebView>
    </androidx.swiperefreshlayout.widget.SwipeRefreshLayout>

JAVA 코드:

  final SwipeRefreshLayout pullToRefresh = findViewById(R.id.swiperefresh);
    pullToRefresh.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
        @Override
        public void onRefresh()
        {
          Toast.makeText(WebBrowser.this,"pull to refresh",Toast.LENGTH_LONG).show();
            mwebView.loadUrl(mainUrl);
            pullToRefresh.setRefreshing(false);//if false then refresh progress dialog will disappear when page loading finish, but if it is true then always the refresh load dialog show even after the page load or not
        }
    });

Build.gradle 소스 코드:

 implementation 'androidx.swiperefreshlayout:swiperefreshlayout:1.1.0'
      

레이아웃에 추가합니다.

<androidx.swiperefreshlayout.widget.SwipeRefreshLayout
        android:id="@+id/swipeRefreshView"
        android:layout_width="match_parent"
        android:layout_height="match_parent"/>

이제 코드에 아래 행을 추가하면 됩니다.

 mSwipeRefreshLayout.setOnRefreshListener(() -> {

       // your refresh code here

    });

다 끝나셨습니다.

언급URL : https://stackoverflow.com/questions/4583484/how-to-implement-android-pull-to-refresh

반응형