0

我正在构建一个 android 应用程序,它要求我在用户第一次启动应用程序时提示用户输入他的名字。在第二次以后,应用程序不会提示用户输入他的名字,而是会向用户打招呼(并立即转到主菜单页面。有人知道我该怎么做吗?

4

2 回答 2

3

将用户名存储在首选项字段中。当应用程序开始检查并查看是否设置了此首选项字段,如果没有,则提示用户输入用户名并保存它,如果已设置,则检索该用户名并在您拥有的活动中使用它:

@Override
protected void onCreate(Bundle savedInstance) {
    super.onCreate(savedInstance);
    final SharedPreferences prefs = PreferenceManager
            .getDefaultSharedPreferences(this);
    String userName = prefs.getString("user_name", null);
    if (userName == null) {
        EditText input = new EditText(this);
        input.setId(1000);          
        AlertDialog dialog = new AlertDialog.Builder(this)
                .setView(input).setTitle("Enter your username!")
                .setPositiveButton("Ok",
                        new DialogInterface.OnClickListener() {

                            @Override
                            public void onClick(DialogInterface dialog,
                                    int which) {
                                EditText theInput = (EditText) ((AlertDialog) dialog)
                                        .findViewById(1000);
                                String enteredText = theInput.getText()
                                        .toString();
                                if (!enteredText.equals("")) {
                                    SharedPreferences.Editor editor = prefs
                                            .edit();
                                    editor.putString("user_name",
                                            enteredText);
                                    editor.commit();
                                }
                            }
                        }).create();
        dialog.show();
    } 
    // you are ready to use the user's username
于 2012-07-21T08:00:00.470 回答
1

Use this code:

        File file = new File("username.txt");

        // if file doesnt exists, then prompt username alert dialog
        if (!file.exists()) {
          //prompt for username
          file.createNewFile();
        }

        FileWriter fw = new FileWriter(file.getAbsoluteFile());
        BufferedWriter bw = new BufferedWriter(fw);
        //suppose  EditText_UserName is your edittext where he can enter his name
        bw.write(EditText_UserName.getText().toString());
        bw.close();

Everytime you start the application, check for this file using file.exists and continue.

于 2012-07-21T07:52:23.340 回答