我将Alert对话框构建器放在if else语句中。现在,我想做的是在“if”语句中自动关闭对话框并在“else”语句中显示对话框。所以,这是我的代码。
public void DisplayConn(){
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle("Error");
builder.setMessage("No Network Connection").setCancelable(false);
AlertDialog alert = builder.create();
if(isNetworkStatusAvailable(getApplicationContext())){
alert.dismiss();
} else {
alert.show();
}
}
我不想使用onClick按钮来关闭对话框,我只想在“if”语句中自动关闭对话框。有可能的?提前谢谢。
答案 0 :(得分:1)
将您的代码更改为:
public void DisplayConn(){
if(!isNetworkStatusAvailable(getApplicationContext())){
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle("Error");
builder.setMessage("No Network Connection").setCancelable(false);
AlertDialog alert = builder.create();
alert.show();
}
}
答案 1 :(得分:0)
你可以这样做......
public void DisplayConn(){
if(!isNetworkStatusAvailable(getApplicationContext())){
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle("Error");
builder.setMessage("No Network Connection").setCancelable(false);
AlertDialog alert = builder.create();
alert.show();
}
}
答案 2 :(得分:0)
您可以尝试以下
public void DisplayConn(){
if(isNetworkStatusAvailable(getApplicationContext())){
Pop.on(this).with().title("Error").cancelable(false).body("No Network Connection").show();
}
}
将此lib包含在您的gradle依赖项中
dependencies {
compile 'com.vistrav:pop:2.0'
}
答案 3 :(得分:0)
我认为BroadcastReciver
会做到这一点。
尝试这样的事情。
if(isNetworkStatusAvailable(getApplicationContext())){
// do your work
} else {
this.registerReceiver(mConnReceiver, new IntentFilter(
ConnectivityManager.CONNECTIVITY_ACTION));
alert.show();
}
您的BroadcastReciver
将如下所示。
private BroadcastReceiver mConnReceiver = new BroadcastReceiver() {
public void onReceive(Context context, Intent intent) {
if (isNetworkStatusAvailable(getApplicationContext())) {
alert.dismiss();
} else {
// do nothing
// Toast.makeText(getApplicationContext(), "Not Connected", 500)
// .show();
}
}
};
和最终任务..您必须在BroadcastReciver
中注册此onResume
并在onPause
中取消注册。
@Override
protected void onPause() {
super.onPause();
Your_class.this.unregisterReceiver(mConnReceiver);
}
protected void onResume() {
super.onResume();
IntentFilter i = new IntentFilter(
"packagename.classname");
Your_class.this.registerReceiver(mConnReceiver, i);
}
我希望这会帮助你。