我知道如何检查互联网连接,在许多活动和片段中,您可以将布局更改为静态视图,表明没有互联网连接。
我想让我的代码更有活力
问题是:如何根据互联网连接更改contentView
?
我可以考虑检查每个Activity
上的互联网是否可用,如果不是,只需更改视图并覆盖onClickListener
,但我不想重复自己。
答案 0 :(得分:0)
编写类似这样的代码,
import android.os.Bundle;
import android.os.Handler;
import android.support.v4.app.FragmentActivity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.FrameLayout;
import android.widget.LinearLayout;
/**
* @author Krish
*/
public abstract class BaseActivity extends FragmentActivity {
protected abstract int getLayoutId();
private LinearLayout connectivtyStateView;
private ViewGroup content;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
FrameLayout conainer = new FrameLayout(this);
conainer.setLayoutParams(new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT,
ViewGroup.LayoutParams.MATCH_PARENT));
this.connectivtyStateView = new LinearLayout(this);
this.connectivtyStateView.setBackgroundResource(R.color.abc);
this.connectivtyStateView.setLayoutParams(new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT,
ViewGroup.LayoutParams.MATCH_PARENT));
conainer.addView(connectivtyStateView);
this.content = (ViewGroup) LayoutInflater.from(this).inflate(getLayoutId(), conainer, true);
setContentView(conainer);
}
@Override
protected void onResume() {
super.onResume();
//registerReceiver()
}
@Override
protected void onPause() {
super.onPause();
// unregisterReceiver();
}
/** Callback for connection change */
private void handleConnectivityChange(boolean isConnected) {
if (isConnected) {
connectivtyStateView.setVisibility(View.GONE);
content.setVisibility(View.VISIBLE);
} else {
connectivtyStateView.setVisibility(View.VISIBLE);
content.setVisibility(View.GONE);
}
}
}
为您的Activities扩展此类,并实现抽象方法以返回内容布局的布局资源ID。