How to add SwipeRefreshLayout to WebView

时间:2016-10-09 15:51:25

标签: android android-layout webview swiperefreshlayout

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

);

2 个答案:

答案 0 :(得分:0)

你必须把你的WebView放在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)停止动画。

答案 1 :(得分:0)

能够使用相同的URL运行

刷新页面
  1. 首页加载时,您必须在ISharedPreferences中保存链接

    public override void OnPageFinished(WebView view, string url)
    {
        ISharedPreferences prefs = PreferenceManager.GetDefaultSharedPreferences(this);
        ISharedPreferencesEditor editor = prefs.Edit();
        editor.PutString("MyURL", url);
        editor.Commit();
    }
    
  2. 加载重新使用的网址时,请使用已保存的网址

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

    - 其他解决方案是  Webview.Reload(); //此代码刷新当前加载的页面