我有一个自定义对话框(扩展Dialog),其内容视图是自定义视图组。视图组有一些edittext子项,但我在viewgroup的dispatchDraw和onTouch方法中处理绘图和单击按钮(我试图避免尽可能多地扩展视图)。 具体来说:此视图没有按钮子项,我可以将其设置为对话框的“关闭”按钮。我想从视图组的onTouch方法中删除对话框,但除了模拟按下后退键之外,我无法弄清楚如何做到这一点。
活动代码:
public class My_Activity extends Activity {
...
public void onCreate(Bundle savedInstanceState) {
...
//if there's no Class_That_Im_Editing in the database, prompt the user to make a new one by adding information to the editviews in this custom dialog and clicking the area where I draw the ok button
my_dialog = new Custom_Dialog(this, R.style.CustomDlg, new Class_That_Im_Editing());
}
}
对话框代码:
public class Custom_Dialog extends Dialog {
...
public void onCreate(Bundle savedInstanceState) {
...
setContentView(new Custom_ViewGroup(context, Class_That_Im_Editing));
}
}
查看组代码:
public class Custom_ViewGroup extends ViewGroup implements OnTouchListener {
//this class has some edittext children but _no_ buttons
...
public boolean onTouch(View view, MotionEvent event) {
if ( logic checking if the user has clicked the button area ) {
//??? what do I put here to dismiss the dialog
}
}
}
我能想到的另一种方法是使用dismissDialog(int)方法,这意味着重写onCreateDialog和onPrepareDialog事件处理程序。但是如何在视图的onTouch方法中调用dismissDialog?
也许我需要建立某种倾听者?如果是这样,那么执行此操作的框架代码是什么?
答案 0 :(得分:1)
所以当我不在对话框存在的范围内时,问题是告诉对话框解除()。这是我的解决方案:
在与对话框相同的范围内创建OnTouchListener - 在本例中,在我的主要活动中。然后在初始化对话框时传递它,然后需要将其传递给视图组。
看起来像这样:
活动代码:
public class My_Activity extends Activity {
public Custom_Dialog my_dialog;
...
public void onCreate(Bundle savedInstanceState) {
OnTouchListener otl_custom_dialog = new OnTouchListener() {
public boolean onTouch(View view, MotionEvent event) {
if ( logic checking if the user has clicked the button area ) {
//notice I can still access any _public_ variable within the viewgroup class
//by using my_dialog.my_custom_viewgroup.public_variable
...
//I can now call dismiss() from within this scope
my_dialog.dismiss();
}
...
}
}
...
//if there's no Class_That_Im_Editing in the database, prompt the user to make a new one by adding information to the editviews in this custom dialog and clicking the area where I draw the ok button
my_dialog = new Custom_Dialog(this, R.style.CustomDlg, new Class_That_Im_Editing(), otl_custom_dialog);
my_dialog.show();
}
}
对话框代码:
public class Custom_Dialog extends Dialog {
Custom_ViewGroup my_custom_viewgroup;
OnTouchListener otl_custom_dialog;
...
public void onCreate(Bundle savedInstanceState) {
...
setContentView(new Custom_ViewGroup(context, class_that_im_editing, otl_custom_dialog));
}
}
查看组代码:
public class Custom_ViewGroup extends ViewGroup implements OnTouchListener {
public Custom_ViewGroup(Context context, Class_That_Im_Editing class_that_im_editing, OnTouchListener otl_custom_dialog) {
...
this.setOnTouchListener(otl_custom_dialog);
}
}
我测试过这种方法,但效果很好。希望这可以帮助其他人!