2012-07-21 16 views

回答

1

使用此代碼:你啓動應用程序

 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(); 

每次,在優先領域檢查該文件中使用file.exists並繼續

+0

是不是這個意思是diff用戶可以使用該應用? – honeybee 2012-07-21 08:32:42

+0

你如何將這個指向另一個頁面?說菜單頁面? – honeybee 2012-07-21 08:42:11

+0

是的。這段代碼將所有用戶視爲相同。如果你想切換用戶,你應該有一個註銷類型的選項,其中你將改變文件的內容。但是如果你想確保不同的用戶使用他們自己的名字輸入,那麼你應該修改你的需求......它應該像應用程序建議每次打開名稱時(而不是直接從文件中讀取)。你是指什麼直接到另一個頁面?如果你的意思是一個新的活動,你可以看看(這裏)[http://stackoverflow.com/a/4186097/1322460] – gkris 2012-07-21 08:49:17

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 
+0

那麼我該如何將這個活動導航到另一個頁面呢?我必須使用新的意圖嗎? – honeybee 2012-07-21 08:28:42

+0

@honeybee您無需從此活動導航。在您擁有的每項活動中(或者您啓動應用程序時用戶將看到的第一項活動),您將放置此代碼。如果用戶沒有用戶名,對話框將會彈出並且用戶名將被保存,否則用戶已經存儲了一個用戶名,並用它來打招呼。在其他活動中,您可以簡單地從首選項中獲取字符串並使用它。 – Luksprog 2012-07-21 08:31:58

+0

用戶名後鍵如何直接進入另一頁?說,主菜單頁面?抱歉太多的問題,因爲我很新的Android編程.. – honeybee 2012-07-21 08:46:40

相關問題