单击后退按钮后如何关闭警报框

时间:2017-06-12 02:28:26

标签: android dialog kotlin alertdialog dismiss

我有调用适配器类的活动。在适配器类中,单击项目后,对话框打开。现在,单击后退按钮后,我无法确定是否关闭此对话框。

这是我的活动课程:

public class MainActivity extends AppCompatActivity{
      protected void onCreate(Bundle savedInstanceState) {

         // fetching the required data
         // blogs is recyclerview
         blogs.setAdapter(new BlogAdapter(MainActivity.this,blogArrayList));
      }


@Override
    public void onBackPressed() {
        //not printed
        Log.i("Back button pressed ","MainActivity");
   }

 @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {

        //not printed
        Log.i("On key down ","Main Activity");
         return super.onKeyDown(keyCode, event);

    }

}

适配器类

class BlogAdapter(var mcontext: Context, var post:ArrayList<Blog>): RecyclerView.Adapter<RecyclerView.ViewHolder>() {

override fun onBindViewHolder(holder: RecyclerView.ViewHolder?, position: Int) {
        holder.itemView.setOnClickListener {
            openDialog(post.get(position),mcontext)
        }
}
 private fun  openDialog(post: Blog?,context:Context) {

        val layoutInflaterAndroid = LayoutInflater.from(context)
        val mView = layoutInflaterAndroid.inflate(R.layout.individual_blog, null)

        val alertDialogBuilder = AlertDialog.Builder(ContextThemeWrapper(context, R.style.AppFullScreen_Dialog_Theme))

        alertDialogBuilder.setView(mView)

        if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.N) {
            mView.title_blog.text = Html.fromHtml(post?.postTitle,Html.FROM_HTML_MODE_LEGACY)
        } else {
            @Suppress("DEPRECATION")
            mView.title_blog.text=Html.fromHtml(post?.postTitle)
        }


        val alertDialog = alertDialogBuilder.create()
        alertDialog!!.show()

        alertDialogBuilder.setOnKeyListener { dialog, keyCode, event ->

            Log.i("Set On Key Listener ","dialog")
            if (keyCode==KeyEvent.KEYCODE_BACK){
                alertDialog.dismiss()
            }
            true
        }

    }
}

2 个答案:

答案 0 :(得分:0)

您可以使用适配器中的上下文显示活动中的对话框,然后检查onBackPressed方法,如果对话框可见,则将其解除,否则为super.onBackPressed()

答案 1 :(得分:0)

这一定有帮助。

  @Override
public void onBackPressed() {
   dialog.dismiss();
}