when a user press button I want to alertdialog which I want is top right. I did something and it works as what I want but on some devices it does not work as I want. I mean it its size is wrong and when I click outside the alertdialog does not disappear , I want it disappear when I click outside.
AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);
builder.setTitle("");
builder.setCancelable(true);
builder.setItems(items , new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int item) {
switch (item) {
case 0:
AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(
MainActivity.this);
// set title
alertDialogBuilder.setTitle(areusure);
alertDialogBuilder.setCancelable(true);
// set dialog message
alertDialogBuilder
.setMessage(clicktologout)
.setCancelable(true)
.setPositiveButton( yes,new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,int id) {
//something
}
})
.setNegativeButton(no_,new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,int id) {
dialog.cancel();
}
});
// create alert dialog
AlertDialog alertDialog = alertDialogBuilder.create();
// show it
alertDialog.show();
break;
case 1:
try {
Intent myIntent = new Intent(MainActivity.this,tutorial.class);
startActivity(myIntent);
} catch (Exception e) {
Toast toast= Toast.makeText(MainActivity.this,
feedus, Toast.LENGTH_LONG);
toast.setGravity(Gravity.CENTER|Gravity.CENTER_HORIZONTAL, 0, 0);
toast.show();
}
break;
case 2:
Intent myIntent = new Intent(MainActivity.this,about.class);
startActivity(myIntent);
break;
}
}
});
AlertDialog alert = builder.create();
alert.requestWindowFeature(Window.FEATURE_NO_TITLE);
alert.setCancelable(true);
WindowManager.LayoutParams wmlp = alert.getWindow().getAttributes();
wmlp.gravity = Gravity.TOP | Gravity.RIGHT;
alert.show();
WindowManager.LayoutParams lp = new WindowManager.LayoutParams();
lp.copyFrom(alert.getWindow().getAttributes());
int value_y = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP,
(float) 42, getResources().getDisplayMetrics());
int value_x = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP,
(float) 20, getResources().getDisplayMetrics());
lp.width = 500;
lp.height = 500;
lp.x=-value_x;
lp.y=value_y;
alert.getWindow().setAttributes(lp);
expected image and wrong image:
Instead of using AlertDialog
and assigning static dimensions and X|Y references on screen, I would suggest you to make use of PopupMenu
which is available in API-11 and above. As for older APIs, you may use support-v7 library.
For example and more info, read this and this.
Moreover, if the dropdown menu is supposed to be anchored from ActionBar, then I would suggest you to stick with the standard menu/group/item implementation rather than going the hard way.