📜  Android 滑动刷新功能(SwipeRefreshLayout)

📅  最后修改于: 2020-10-11 05:54:02             🧑  作者: Mango

滑动即可刷新Android活动(SwipeRefreshLayout)

在本教程中,我们将在Android中创建刷卡刷新功能。为此,应使用SwipeRefreshLayout小部件。

SwipeRefreshLayout的实例添加了OnRefreshListener方法,并实现了将在刷新时加载的代码逻辑。当用户滑动时,垂直滑动会显示一个独特的进度条。进度栏显示进度动画时调用setRefreshing(true)或调用setRefreshing(false)取消。

滑动以刷新Android活动示例

在activity_main.xml文件中,实现SwipeRefreshLayout小部件。

activity_main.xml




    

        
    

创建一个活动MainActivity.java并添加以下代码。在此类中,我们将检查滑动的onRefresh()网络连接。

MainActivity.java

package example.javatpoint.com.swiperefreshlayout;

import android.content.Context;
import android.graphics.Color;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.TextView;

public class MainActivity extends AppCompatActivity {
    SwipeRefreshLayout swipeRefreshLayout;
    TextView textView;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        swipeRefreshLayout = findViewById(R.id.refreshLayout);
        textView = findViewById(R.id.textView);
        swipeRefreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {
                       swipeRefreshLayout.setRefreshing(false);
                       //your code on swipe refresh
                       //we are checking networking connectivity
                        boolean connection=isNetworkAvailable();
                        if(connection){
                            textView.setText("internet connect");
                            textView.setTextColor(Color.GREEN);
                        }
                        else{
                            textView.setText("not connected");
                            textView.setTextColor(Color.RED);
                        }

            }
        });
        swipeRefreshLayout.setColorSchemeColors(Color.YELLOW);
    }
    public boolean isNetworkAvailable(){

        ConnectivityManager connectivityManager=(ConnectivityManager) this.getApplicationContext().getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo networkInfo=connectivityManager.getActiveNetworkInfo();
        return networkInfo !=null;
    }
}

所需权限

在AndroidMenifest.xml文件中添加uses-permission。下面给出的权限用于访问网络连接。