Abed
Abed

Reputation: 5187

How to add SwipeRefreshLayout to WebView

I need to pull from the top to refresh my web view I found this on Android Developer site but i don't know how to use it

xml Code

<android.support.v4.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">

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

Java code

mySwipeRefreshLayout.setOnRefreshListener(
new SwipeRefreshLayout.OnRefreshListener() {
    @Override
    public void onRefresh() {
        Log.i(LOG_TAG, "onRefresh called from SwipeRefreshLayout");

        // This method performs the actual data-refresh operation.
        // The method calls setRefreshing(false) when it's finished.
        myUpdateOperation();
    }
}

);

Upvotes: 1

Views: 9040

Answers (2)

Ehab Naim
Ehab Naim

Reputation: 11

To be able to refresh the page with the same URL running

  1. you gotta save your link in ISharedPreferences when page first loaded

    public override void OnPageFinished(WebView view, string url)
    {
        ISharedPreferences prefs = PreferenceManager.GetDefaultSharedPreferences(this);
        ISharedPreferencesEditor editor = prefs.Edit();
        editor.PutString("MyURL", url);
        editor.Commit();
    }
    
  2. when you load the URL for reffresh use the saved URL

    string SaveURL = prefs.GetString("MyURL", "");
    webView.loadUrl(SaveURL);
    

    -- Other Solution is Webview.Reload(); // This code Refreshes the current page loaded

Upvotes: 1

Figen G&#252;ng&#246;r
Figen G&#252;ng&#246;r

Reputation: 12559

You gotta put your WebView inside SwipeRefreshLayout:

public class MainActivity extends AppCompatActivity {

    WebView webView;
    SwipeRefreshLayout swipeRefreshLayout;
    String currentUrl = "https://news.ycombinator.com/";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        webView = (WebView) findViewById(R.id.webView);
        swipeRefreshLayout = (SwipeRefreshLayout) findViewById(R.id.swipeRefreshLayout);

        webView.loadUrl(currentUrl);
        webView.setWebViewClient(new MyWebViewClient());

        swipeRefreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {
                webView.loadUrl(currentUrl);
            }
        });


    }

    public class MyWebViewClient extends WebViewClient{

        @Override
        public void onPageFinished(WebView view, String url) {
            swipeRefreshLayout.setRefreshing(false);
            currentUrl = url;
            super.onPageFinished(view, url);
        }
    }


}

swipeRefreshLayout.setRefreshing(false) stops the animation.

Upvotes: 3

Related Questions