📅  最后修改于: 2020-10-11 05:54:02             🧑  作者: Mango
在本教程中,我们将在Android中创建刷卡刷新功能。为此,应使用SwipeRefreshLayout小部件。
SwipeRefreshLayout的实例添加了OnRefreshListener方法,并实现了将在刷新时加载的代码逻辑。当用户滑动时,垂直滑动会显示一个独特的进度条。进度栏显示进度动画时调用setRefreshing(true)或调用setRefreshing(false)取消。
在activity_main.xml文件中,实现SwipeRefreshLayout小部件。
创建一个活动MainActivity.java并添加以下代码。在此类中,我们将检查滑动的onRefresh()网络连接。
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。下面给出的权限用于访问网络连接。