2011年9月28日 星期三

[Android] How to block back and search button on Dialog?

It will cancel dialog If user press back or search button on dialog. Therefore, sometimes we need to block back and search button on dialog to ensure the logic of dialog can work normally.
		public void alertDialog(final String title, final String msg, final String btn1, final String btn2, final String btn3, final String cmd, final String data)
		{
			AlertDialog.Builder MyAlertDialog = new AlertDialog.Builder(self);
			MyAlertDialog.setIcon(android.R.drawable.ic_dialog_alert);
			MyAlertDialog.setTitle(title);
			MyAlertDialog.setMessage(msg);
			MyAlertDialog.setCancelable(false); // block back button

			MyAlertDialog.setOnKeyListener(new DialogInterface.OnKeyListener()
			{
				@Override
				public boolean onKey(DialogInterface dialog, int keyCode, KeyEvent event)
				{
					if (keyCode==KeyEvent.KEYCODE_SEARCH)	// block search button
						return true;
					else
						return false;
				}
			});

			DialogInterface.OnClickListener OkClick = new DialogInterface.OnClickListener() {
				public void onClick(DialogInterface dialog, int which) {
				// Handle onClick
				}
			};
			if (btn1 != null)
				MyAlertDialog.setPositiveButton(btn1, OkClick );
			if (btn2 != null)
				MyAlertDialog.setNegativeButton(btn2, OkClick );
			if (btn3 != null)
				MyAlertDialog.setNeutralButton(btn3, OkClick );

			 MyAlertDialog.show();
		}

沒有留言:

張貼留言