我需要向在我的Android应用上点击按钮的用户显示一条小文本消息,在IOS上,我只需创建一个很容易使用的AlertView即可,但在Android上我很苦恼,因为解决方案似乎要难十倍。我看到需要使用DialogFragment,但我无法理解如何使其工作,有人能解释一下吗?另外,我的解决方案是否正确,或者有更简单的方法向用户显示简单的文本消息?
我需要向在我的Android应用上点击按钮的用户显示一条小文本消息,在IOS上,我只需创建一个很容易使用的AlertView即可,但在Android上我很苦恼,因为解决方案似乎要难十倍。我看到需要使用DialogFragment,但我无法理解如何使其工作,有人能解释一下吗?另外,我的解决方案是否正确,或者有更简单的方法向用户显示简单的文本消息?
您只需要在onClick
中执行此操作:
AlertDialog alertDialog = new AlertDialog.Builder(MainActivity.this).create();
alertDialog.setTitle("Alert");
alertDialog.setMessage("Alert message to be shown");
alertDialog.setButton(AlertDialog.BUTTON_NEUTRAL, "OK",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
});
alertDialog.show();
我不知道你从哪里得出需要使用 DialogFragment 来显示警报的结论。
不是的,我的朋友。很简单,试试用这个:
AlertDialog alertDialog = new AlertDialog.Builder(AlertDialogActivity.this).create();
alertDialog.setTitle("Alert Dialog");
alertDialog.setMessage("Welcome to dear user.");
alertDialog.setIcon(R.drawable.welcome);
alertDialog.setButton(AlertDialog.BUTTON_POSITIVE, "OK", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
Toast.makeText(getApplicationContext(), "You clicked on OK", Toast.LENGTH_SHORT).show();
}
});
alertDialog.show();
这个教程展示了如何使用xml创建自定义对话框,并将它们显示为警告对话框。
你可以轻松地制作自己的“AlertView”并在任何地方使用它。
alertView("You really want this?");
只需实现一次:
private void alertView( String message ) {
AlertDialog.Builder dialog = new AlertDialog.Builder(context);
dialog.setTitle( "Hello" )
.setIcon(R.drawable.ic_launcher)
.setMessage(message)
// .setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
// public void onClick(DialogInterface dialoginterface, int i) {
// dialoginterface.cancel();
// }})
.setPositiveButton("Ok", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialoginterface, int i) {
}
}).show();
}
context
?我正在使用androidx.appcompat.app.AlertDialog
。 - Jeson Martajaya