如何在没有引用对话框的情况下从OnClick中删除对话框

时间:2015-10-05 20:35:55

标签: android

我有一个类有一个方法,通过调用它显示一个对话框。该对话框具有按钮,其中包含侦听器。 问题是,当onClick被触发时,我无法获得对话框,所以我可以解雇。在这种情况下我该怎么办?我不想将对话框存储为变量,因为这是静态类,并且不想持有对话框的引用

public void onClick(View v) {
        switch(v.getId()){
        case R.id.bActionUpgradeSword:
            // do action

            break;
        case R.id.bActionUpgradeArmor:
                // do action        
            break;  
        }

      // I WANT TO DISMISS DIALOG HERE
    }

private void showUpgradeSwordDiag(Activity act){
         Dialog diag = new Dialog(act);
        diag.requestWindowFeature(Window.FEATURE_NO_TITLE);
        diag.setContentView(R.layout.diag_upgrade_sword_dialog);
        /* add some info to dialog */
        /* set the click listeners */
        diag.show()
}

3 个答案:

答案 0 :(得分:0)

试试这个:

public void onClick(View v) {
            switch(v.getId()){
            case R.id.bActionUpgradeSword:
                // do action
                if(diag!=null){
                diag.dismiss();   
                }
                break;
            case R.id.bActionUpgradeArmor:
                    // do action        
                break;  
            }

          // I WANT TO DISMISS DIALOG HERE
        }
     Dialog diag;
    private void showUpgradeSwordDiag(Activity act){
             diag = new Dialog(act);
            diag.requestWindowFeature(Window.FEATURE_NO_TITLE);
            diag.setContentView(R.layout.diag_upgrade_sword_dialog);
            /* add some info to dialog */
            /* set the click listeners */
            diag.show()
    }

答案 1 :(得分:0)

创建一个实现DialogInterface.OnClickListener的类,并根据需要覆盖onClick方法。像这样的东西:

public void onClick (DialogInterface dialog, int which) {
 switch(which){
  case BUTTON_NEGATIVE:
   dialog.dismiss();
   break;
 }
}

答案 2 :(得分:-1)

尝试在视图中将对话框设置为标记,然后获取如下标记

 Dialog diag = null;
 Button b = null;
 b.setTag(diag);
 Dialog d = (Dialog) b.getTag();