I want to add OnclickListener for a button,where in I want to display the Dialog box on the left of the screen on click of it.I tried to implement that but it always appears on the center of the screen.Any idea on how to implement that?
问题:
回答1:
If I understand your question correctly - you want to align your dialog not appear on the center of the screen. Then look at this code sample.
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setItems(items, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int item) {
if(item == 0) {
} else if(item == 1) {
} else if(item == 2) {
}
}
});
AlertDialog dialog = builder.create();
dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
WindowManager.LayoutParams WMLP = dialog.getWindow().getAttributes();
WMLP.x = 100; //x position
WMLP.y = 100; //y position
dialog.getWindow().setAttributes(WMLP);
dialog.show();
Here x position's value is pixels from left to right. For y position value is from bottom to top.
回答2:
Before calling #show()
on your AlertDialog
you can adjust the gravity of the dialog window:
AlertDialog dlg = ...;
dlg.getWindow().getAttributes().gravity = Gravity.LEFT|Gravity.CENTER_VERTICAL;
This would shift the dialog to the left of the screen. Adjust your gravity flags according to your taste.
回答3:
Just add following line in your java file and extra space will remove from dialog box.
Dialog dialog; dialog=new Dialog(Activity.this,android.R.style.Theme_DeviceDefault_Light_Panel);
Above code work for me. I hope it will be work for others too. Note: You need to pass activity context instead of normal context (getApplicationContext()).