废话不说,直接上代码
父类
protected StateLayoutManager statusLayoutManager;
private BroadcastReceiver broadcastReceiver = new InternetBroadcastReceiver(this);
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
int layoutId = initView(savedInstanceState);
setContentView(R.layout.activity_main);
//注册广播
IntentFilter intentFilter = new IntentFilter(ConnectivityManager.CONNECTIVITY_ACTION);
registerReceiver(broadcastReceiver, intentFilter);
initStatusLayout(layoutId);
initBaseView();
initView();
}
protected void initStatusLayout(int a) {
statusLayoutManager = StateLayoutManager.newBuilder(this)
.contentView(a)
.emptyDataView(R.layout.activity_emptydata)
.errorView(R.layout.activity_error)
.loadingView(R.layout.activity_loading)
.netWorkErrorView(R.layout.activity_networkerror)
.build();
}
protected abstract void initView();
/**
* 获取到布局
*/
private void initBaseView() {
LinearLayout ll_main = (LinearLayout) findViewById(R.id.ll_main);
ll_main.addView(statusLayoutManager.getRootLayout());
}
//正常展示数据状态
protected void showContent() {
statusLayoutManager.showContent();
}
//加载数据为空时状态
protected void showEmptyData() {
statusLayoutManager.showEmptyData();
}
//加载数据错误时状态
protected void showError() {
statusLayoutManager.showError();
}
//网络错误时状态
protected void showNetWorkError() {
statusLayoutManager.showNetWorkError();
}
//正在加载中状态
protected void showLoading() {
statusLayoutManager.showLoading();
}
/**
* 网络中断
*/
public void onError() {
showNetWorkError();
ConstraintLayout ll_set_network = (ConstraintLayout) findViewById(R.id.ll_set_network);
ll_set_network.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Intent intent = new Intent("android.settings.WIRELESS_SETTINGS");
startActivity(intent);
}
});
}
/**
* 网络连接成功
*/
protected void onConnect() {
showContent();
}
@Override
protected void onDestroy() {
super.onDestroy();
//解除广播
unregisterReceiver(broadcastReceiver);
}
广播
public class InternetBroadcastReceiver extends BroadcastReceiver {
private BaseMainActivity mContext;
public InternetBroadcastReceiver(BaseMainActivity mainActivity) {
mContext = mainActivity;
}
@Override
public void onReceive(Context context, Intent intent) {
final ConnectivityManager connectivityManager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
if (connectivityManager != null) {
NetworkInfo activeNetworkInfo = connectivityManager.getActiveNetworkInfo();
if (activeNetworkInfo!=null && activeNetworkInfo.isConnected()){
Log.d("网络链接成功","网络链接成功");
mContext.onConnect();
}else {
Log.d("网络断开","网络断开");
mContext.onError();
}
}
}
}
接口
public interface IActivity {
/**
* 初始化 View
*
* @param savedInstanceState
* @return
*/
int initView(@Nullable Bundle savedInstanceState);
}
怎么使用呢?让自己的页面继承 BaseMainActivity
@Override
public int initView(@Nullable Bundle savedInstanceState) {
return R.layout.activity_main2;
}
@Override
protected void initView() {
}
一切OK,完美!最后附上项目下载链接