通过反射重新设置Dialog:
//通过反射得到dialog对象
field = dialog.getClass().getSuperclass().getDeclaredField(“mShowing”);
filed.setAccessible(true);//取消默认 Java 语言访问控制检查,这样可以调用外部的private方法
field.set(dialog, true);//dialog消失
field.set(dialog, false);//dialog不消失
代码示例, 使用showDialog(int dialogid)方法提示是否清空EdutText的内容:
public classDialogTest extends Activity {
private static final int DIALOG_CLEAN = 1; // 清空文字
private EditText edit; //要提交的内容
@Override
protected void onCreate(Bundle icicle) {
super.onCreate(icicle);
setContentView(R.layout.bbs_topic_new_activity);
//初始化控件
...
edit.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
clean();
}
});
}
@Override
protected Dialog onCreateDialog(int id) {
Builder builder = null;
switch (id) {
case DIALOG_CLEAN:
builder = new AlertDialog.Builder(this)
.setTitle("提示")
.setMessage("确认清除全部内容?")
.setPositiveButton("确定",
new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog,
int which) {
edit.setText("");
}
})
.setNeutralButton("取消",
new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog,
int which) {
disappearDialog(dialog);
}
});
break;
default:
break;
}
return builder.create();
}
/**
* 清除文字
*/
private void clean() {
String content = edit.getText().toString();
if (!content.equals("")) {
showDialog(DIALOG_CLEAN);
}
}
private void disappearDialog(DialogInterface dialog) {
try {
Field field = dialog.getClass().getSuperclass()
.getDeclaredField("mShowing");
field.setAccessible(true);
field.set(dialog, true);
} catch (Exception e) {
e.printStackTrace();
}
}
}
-