虽然没有提到在按下中性按钮时关闭或关闭我的对话框,但我的应用程序仍然觉得需要在按下对话框时关闭对话框。
有什么想法吗?
dialogBox = (AlertDialog) dialogBoxHandler.locationDialog();
dialogBox.setButton(DialogInterface.BUTTON_NEUTRAL, "Use Current Location", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
EditText latitude = (EditText) dialogBox.findViewById(R.id.dl_et_latitude);
EditText longitude = (EditText) dialogBox.findViewById(R.id.dl_et_longitude);
LocationManager lm = (LocationManager) MessageSelection.this.getSystemService(Context.LOCATION_SERVICE);
try {
Location location = lm.getLastKnownLocation(LocationManager.GPS_PROVIDER);
double currentLongitude = location.getLongitude();
double currentLatitude = location.getLatitude();
latitude.setText(Double.toString(currentLatitude));
longitude.setText(Double.toString(currentLongitude));
Log.d(TAG, "Latitude " + currentLatitude + " Longitude " + currentLongitude);
} catch (SecurityException e){
Log.d(TAG, e.toString());
}
}
});
dialogBox.show();
最佳答案
原来需要一个 OnShowListener 并且必须在其中定义 onClickListener。如果在使用 DialogBuilder 时尝试定义中性按钮功能,或者在创建对话框后(以及显示之前)设置按钮功能,这将不起作用。
dialogBuilder.setView(inflater.inflate(R.layout.dialog_location, null))
.setNeutralButton("Use Current Location", null);
final AlertDialog locationDialog = dialogBuilder.create();
locationDialog.setOnShowListener(new DialogInterface.OnShowListener() {
@Override
public void onShow(DialogInterface dialog) {
Button button = ((AlertDialog) dialog).getButton(AlertDialog.BUTTON_NEUTRAL);
button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
EditText latitude = (EditText) locationDialog.findViewById(R.id.dl_et_latitude);
EditText longitude = (EditText) locationDialog.findViewById(R.id.dl_et_longitude);
LocationManager lm = (LocationManager) context.getSystemService(Context.LOCATION_SERVICE);
try {
Location location = lm.getLastKnownLocation(LocationManager.GPS_PROVIDER);
double currentLongitude = location.getLongitude();
double currentLatitude = location.getLatitude();
latitude.setText(Double.toString(currentLatitude));
longitude.setText(Double.toString(currentLongitude));
Log.d(TAG, "Latitude " + currentLatitude + " Longitude " + currentLongitude);
} catch (SecurityException e){
Log.d(TAG, e.toString());
}
}
});
}
});
关于java - AlertDialog 中性按钮关闭对话框,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43572729/