安装应用程序后,将弹出一个alertDialog
。我希望它有一个编辑文本字段,要求输入用户名。回答后就不会再出现了。然后,每次我打开应用程序时,都会弹出另一个 alertDialog
,就像向用户打招呼一样。
public class MainActivity extends Activity {
final Context context = this;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
AlertDialog.Builder alert = new AlertDialog.Builder(context);
alert.setTitle("Welcome");
alert.setMessage("Enter Your Name Here");
final EditText input = new EditText(context);
alert.setView(input);
alert.setPositiveButton("OK", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
}
});
AlertDialog alertDialog = alert.create();
alertDialog.show();
AlertDialog.Builder a_builder = new AlertDialog.Builder(MainActivity.this);
a_builder.setMessage("Mabuhay!")
.setCancelable(true)
.setPositiveButton("ok", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
dialog.cancel();
}
});
AlertDialog alert = a_builder.create();
alert.show();
}
}
最佳答案
用户首次打开应用程序时输入其姓名后,您可以将给定的用户名写入 SharedPreferences您的应用程序。
当用户现在在任何其他时间打开应用程序时,您只需检查应用程序的共享首选项中是否有条目,并使用适当的用户名向用户致意。
//instance variable in the Mainactivity.class
private boolean showMessage = true;
SharedPreferences sharedPref = getActivity().getPreferences(Context.MODE_PRIVATE);
String username = sharedPref.getString("username", null);
if(username == null){
//first time user - ask for username
SharedPreferences.Editor editor = sharedPref.edit();
editor.putString("username", enteredName);
editor.commit();
showMessage = false;
} else if(showMessage) {
showMessage = false;
//greet
AlertDialog.Builder alert = new AlertDialog.Builder(MainActivity.this);
alert.setMessage("Hello " + username + "!")
.setCancelable(true)
.setPositiveButton("ok", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
dialog.cancel();
}
});
alert.create().show();
}
关于java - 如何让alertDialog在每次运行我的应用程序时弹出?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34561102/