[Android] 웹뷰 내 스크롤로 새로고침 하기(화면 상단 스크롤 새로고침)
[새로고침]
안드로이드에서 새로고침을 하는 방법은 간단하다. Webview.reload()이 함수인데, 새로고침을 위해 버튼을 하단에 생성하여 연결하는 경우가 많은데.. 이 경우 말고, 화면을 아래로 드래그했을 때.. 즉 웹뷰 내 스크롤 Y값이 0일 때 이 새로고침을 수행하게 하면 되는 것이다.
[준비]
이 새로고침을 사용하는 가장 기본히 되는 레이아웃이 있다. SwipeRefreshLayout이란 것인데 말 그대로 새로고침을 위한 레이아웃이랄까.
레이아웃 파일에서 웹뷰를 감싸는 뷰로 이 스와이프 리프레쉬 레이아웃을 사용한다.
<android.support.v4.widget.swiperefreshlayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="@+id/contentSwipeLayout"> <webview android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="@+id/contentWebView"
android:layout_weight="1"> </webview> </android.support.v4.widget.SwipeRefreshLayout>
그리고 액티비티 클래스파일에서는
import android.app.DownloadManager; import android.content.Intent; import android.net.Uri; import android.os.Build; import android.os.Bundle; import android.os.Environment; import android.support.v4.widget.SwipeRefreshLayout; import android.support.v7.app.AppCompatActivity; import android.util.Log; import android.view.ViewTreeObserver; import android.webkit.DownloadListener; import android.webkit.WebSettings; import android.webkit.WebView; import android.widget.Toast; public class ContentActivity extends AppCompatActivity { SwipeRefreshLayout refreshLayout; WebView contentWebView; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_content); refreshLayout = (SwipeRefreshLayout) findViewById(R.id.contentSwipeLayout); contentWebView = (WebView) findViewById(R.id.contentWebView); refreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() { @Override public void onRefresh() { contentWebView.reload(); } }); refreshLayout.getViewTreeObserver().addOnScrollChangedListener(new ViewTreeObserver.OnScrollChangedListener() { @Override public void onScrollChanged() { if(contentWebView.getScrollY() == 0){ refreshLayout.setEnabled(true); } else { refreshLayout.setEnabled(false); } } }); Intent getIntent = getIntent(); String url = getIntent.getStringExtra("url"); if(url != null){ contentWebView.loadUrl(url); } } }
웹뷰에 대한 세팅이나 설정은 제외했다. 이는 따로 포스팅할 것이고..
어쨌든, 저 SwipeRefreshLayout에 리스너와 함께 스크롤 체인지 이벤트를 걸어준다. 즉, refreshLayout.setEnabled가 true가 되면 onRefresh가 실행되게 되어 웹뷰의 reload()가 실행되는 원리이다.
사용자 입장에서는 버튼을 누르지않아도.. 이 방법이 편해지면 이것만 쓰게 된다.