[Android] 设置AlertDialog打开后不消失

时间:2023-03-09 18:50:10
[Android] 设置AlertDialog打开后不消失

最近项目收尾,一堆bug要改,还要对用户操作体验做一些优化,也是忙的不行。周末难得清闲,出去逛逛,看看风景,还好因为习大大要来,南京最近的天气还不错,只是苦了当地的不少农民工,无活可干,无钱可拿。想想觉得自己已经算是幸运的了,心存感激,好好工作。

原文地址请保留 http://www.cnblogs.com/rossoneri/p/4150001.html

整理一下以前查过的东西,可惜笔记本没记多少资料博客的网址,没法贴资料地址。

关于本文,是要满足一个需求:

打开一个自定义对话框之后,再点击按钮,希望弹出一个确认之类的对话框显示在前端,同时不希望原来的对话框消失。

方法就是用反射机制获取相关字段进行设置:

Field field = dialog.getClass().getSuperclass().getDeclaredField("mShowing");
field.setAccessible(true);
field.set(dialog, false);

关于getDeclaredField()往后再研究下。

写了个简单的demo:

 public class MainActivity extends ActionBarActivity {

     Button btn;

     @Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main); btn = (Button) findViewById(R.id.btn);
btn.setOnClickListener(new OnClickListener() { @Override
public void onClick(View v) {
// TODO Auto-generated method stub
AlertDialog.Builder builder = new Builder(MainActivity.this,
AlertDialog.THEME_HOLO_LIGHT);
builder.setTitle("Test");
builder.setMessage("Try to push the OK button and the dialog won`t be dismissed, do it now !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!");
builder.setPositiveButton("OK",
new DialogInterface.OnClickListener() { @Override
public void onClick(DialogInterface dialog,
int which) {
// TODO Auto-generated method stub
try {
Field field = dialog.getClass()
.getSuperclass()
.getDeclaredField("mShowing");
field.setAccessible(true);
field.set(dialog, false); // 此处设为true则可以关闭
} catch (Exception e) {
e.printStackTrace();
} AlertDialog.Builder confirmDlg = new Builder(
MainActivity.this,
AlertDialog.THEME_HOLO_DARK);
confirmDlg.setTitle("confirm");
confirmDlg
.setMessage("Do you want to do the action?");
confirmDlg.create().show(); }
}); builder.setNegativeButton("Cancel",
new DialogInterface.OnClickListener() { @Override
public void onClick(DialogInterface dialog,
int which) {
// TODO Auto-generated method stub
try {
Field field = dialog.getClass()
.getSuperclass()
.getDeclaredField("mShowing");
field.setAccessible(true);
field.set(dialog, true);
} catch (Exception e) {
e.printStackTrace();
}
}
}); builder.create().show();
}
}); }
}