0

我創建了一個包含用戶名密碼登錄按鈕和更改語言選項(包含所需語言的下拉列表)的登錄頁面。在android中實現國際化

登錄頁面

enter image description here

enter image description here

我的問題是如何將國際化的所有pages.Suppose是否應該被應用到登錄頁面,以及接下來的點擊法國login.Please幫助後,網頁..

MainActivity.java

package com.example.login11; 


import java.util.HashMap; 

import android.os.Bundle; 
import android.support.v7.app.ActionBarActivity; 
import android.text.Html; 
import android.view.View; 
import android.widget.Button; 
import android.widget.TextView; 
import android.widget.Toast; 

public class MainActivity extends ActionBarActivity 
{ 

    // User Session Manager Class 
    UserSessionManager session; 

// Button Logout 
    Button btnLogout; 
    @Override 
    protected void onCreate(Bundle savedInstanceState) { 
     super.onCreate(savedInstanceState); 
     setContentView(R.layout.activity_main); 


     // Session class instance 
     session = new UserSessionManager(getApplicationContext()); 

     TextView lblName = (TextView) findViewById(R.id.lblName); 
     TextView lblEmail = (TextView) findViewById(R.id.lblEmail); 

     // Button logout 
     btnLogout = (Button) findViewById(R.id.btnLogout); 

     Toast.makeText(getApplicationContext(), 
         "User Login Status: " + session.isUserLoggedIn(), 
         Toast.LENGTH_LONG).show(); 



     // Check user login (this is the important point) 
     // If User is not logged in , This will redirect user to LoginActivity 
     // and finish current activity from activity stack. 
     if(session.checkLogin()) 
      finish(); 

     // get user data from session 
     HashMap<String, String> user = session.getUserDetails(); 

     // get name 
     String name = user.get(UserSessionManager.KEY_NAME); 

     // get email 
     String email = user.get(UserSessionManager.KEY_EMAIL); 

     // Show user data on activity 
     lblName.setText(Html.fromHtml("Name: <b>" + name + "</b>")); 
     lblEmail.setText(Html.fromHtml("Email: <b>" + email + "</b>")); 


     btnLogout.setOnClickListener(new View.OnClickListener() { 

      @Override 
      public void onClick(View arg0) { 

       // Clear the User session data 
       // and redirect user to LoginActivity 
       session.logoutUser(); 
      } 
     }); 
    } 

} 

LoginActivity.java

package com.example.login11; 



import android.content.Intent; 
import android.os.Bundle; 
import android.support.v7.app.ActionBarActivity; 
import android.view.View; 
import android.widget.ArrayAdapter; 
import android.widget.Button; 
import android.widget.EditText; 
import android.widget.Spinner; 
import android.widget.Toast; 

public class LoginActivity extends ActionBarActivity 
{ 
    Button btnLogin; 

    EditText txtUsername, txtPassword; 
    private Spinner language; 
    // User Session Manager Class 
    UserSessionManager session; 
    @Override 
    protected void onCreate(Bundle savedInstanceState) { 
     super.onCreate(savedInstanceState); 
     setContentView(R.layout.activity_login); 

     // User Session Manager 
     session = new UserSessionManager(getApplicationContext());     

     // get Email, Password input text 
     txtUsername = (EditText) findViewById(R.id.txtUsername); 
     txtPassword = (EditText) findViewById(R.id.txtPassword); 
     language = (Spinner) findViewById(R.id.spinner1); 
     Toast.makeText(getApplicationContext(), 
       "User Login Status: " + session.isUserLoggedIn(), 
       Toast.LENGTH_LONG).show(); 


     // User Login button 
     btnLogin = (Button) findViewById(R.id.btnLogin); 

    // Spinner method to read the on selected value 
      ArrayAdapter<State> spinnerArrayAdapter = new ArrayAdapter<State>(this, 
        android.R.layout.simple_spinner_item, new State[] { 
          new State("english"), new State("french") }); 
      language.setAdapter(spinnerArrayAdapter); 
      //language.setOnItemSelectedListener(this); 
     // Login button click event 
     btnLogin.setOnClickListener(new View.OnClickListener() { 

      @Override 
      public void onClick(View arg0) { 

       // Get username, password from EditText 
       String username = txtUsername.getText().toString(); 
       String password = txtPassword.getText().toString(); 

       // Validate if username, password is filled    
       if(username.trim().length() > 0 && password.trim().length() > 0){ 

        // For testing puspose username, password is checked with static data 
        // username = admin 
        // password = admin 

        if(username.equals("admin") && password.equals("admin")){ 


         session.createUserLoginSession("Android Example", 
          "[email protected]"); 

         // Starting MainActivity 
         Intent i = new Intent(getApplicationContext(), MainActivity.class); 
         i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP); 

         // Add new Flag to start new Activity 
         i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK); 
         startActivity(i); 

         finish(); 

        }else{ 

         // username/password doesn't match& 
         Toast.makeText(getApplicationContext(), 
          "Username/Password is incorrect", 
           Toast.LENGTH_LONG).show(); 

        }    
       }else{ 

        // user didn't entered username or password 
        Toast.makeText(getApplicationContext(), 
         "Please enter username and password", 
           Toast.LENGTH_LONG).show(); 

       } 

      } 
     }); 
    } 

} 

userSession.java

package com.example.login11; 

import java.util.HashMap; 

import android.content.Context; 
import android.content.Intent; 
import android.content.SharedPreferences; 
import android.content.SharedPreferences.Editor; 

public class UserSessionManager 
{ 
    // Shared Preferences reference 
    SharedPreferences pref; 

    // Editor reference for Shared preferences 
    Editor editor; 

    // Context 
    Context _context; 

    // Shared pref mode 
    int PRIVATE_MODE = 0; 

    // Sharedpref file name 
    private static final String PREFER_NAME = "AndroidExamplePref"; 

    // All Shared Preferences Keys 
    private static final String IS_USER_LOGIN = "IsUserLoggedIn"; 

    // User name (make variable public to access from outside) 
    public static final String KEY_NAME = "name"; 

    // Email address (make variable public to access from outside) 
    public static final String KEY_EMAIL = "email"; 

    // Constructor 
    public UserSessionManager(Context context){ 
     this._context = context; 
     pref = _context.getSharedPreferences(PREFER_NAME, PRIVATE_MODE); 
     editor = pref.edit(); 
    } 

    //Create login session 
    public void createUserLoginSession(String name, String email){ 
     // Storing login value as TRUE 
     editor.putBoolean(IS_USER_LOGIN, true); 

     // Storing name in pref 
     editor.putString(KEY_NAME, name); 

     // Storing email in pref 
     editor.putString(KEY_EMAIL, email); 

     // commit changes 
     editor.commit(); 
    } 

    /** 
    * Check login method will check user login status 
    * If false it will redirect user to login page 
    * Else do anything 
    * */ 
    public boolean checkLogin(){ 
     // Check login status 
     if(!this.isUserLoggedIn()){ 

      // user is not logged in redirect him to Login Activity 
      Intent i = new Intent(_context, LoginActivity.class); 

      // Closing all the Activities from stack 
      i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP); 

      // Add new Flag to start new Activity 
      i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK); 

      // Staring Login Activity 
      _context.startActivity(i); 

      return true; 
     } 
     return false; 
    } 



    /** 
    * Get stored session data 
    * */ 
    public HashMap<String, String> getUserDetails(){ 

     //Use hashmap to store user credentials 
     HashMap<String, String> user = new HashMap<String, String>(); 

     // user name 
     user.put(KEY_NAME, pref.getString(KEY_NAME, null)); 

     // user email id 
     user.put(KEY_EMAIL, pref.getString(KEY_EMAIL, null)); 

     // return user 
     return user; 
    } 

    /** 
    * Clear session details 
    * */ 
    public void logoutUser(){ 

     // Clearing all user data from Shared Preferences 
     editor.clear(); 
     editor.commit(); 

     // After logout redirect user to Login Activity 
     Intent i = new Intent(_context, LoginActivity.class); 

     // Closing all the Activities 
     i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP); 

     // Add new Flag to start new Activity 
     i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK); 

     // Staring Login Activity 
     _context.startActivity(i); 
    } 


    // Check for login 
    public boolean isUserLoggedIn(){ 
     return pref.getBoolean(IS_USER_LOGIN, false); 
    } 
} 

回答

0

你可以做這樣的事情:

public class LanguagePesistence { 

    SharedPreferences pref; 
    Editor editor; 
    Context _context; 
    int PRIVATE_MODE = 0; 

    private static final String PREF_NAME = "LanguagePesistence"; 

    public static final String LANGUAGE_DEFAULT = Locale.getDefault().getLanguage(); 
    public static final String LANGUAGE = "language"; 

    public LanguagePesistence(Context context){ 
     this._context = context; 
     pref = _context.getSharedPreferences(PREF_NAME, PRIVATE_MODE); 
     editor = pref.edit(); 
    } 

    public String getLanguageSelected(){ 
     return pref.getString(LANGUAGE, LANGUAGE_DEFAULT); 
    } 

    public void setLanguage(String language){ 
     editor.putString(LANGUAGE, language);   
     editor.commit(); 
     alterIdioma(language); 
    } 

    public void alterIdioma(String languageToLoad){ 

     Locale locale = new Locale(languageToLoad); 
     Locale.setDefault(locale); 
     Configuration config = new Configuration(); 
     config.locale = locale; 
     Resources res = this._context.getResources(); 
     res.updateConfiguration(config, res.getDisplayMetrics()); 
    } 
} 

要設置語言

LanguagePesistence lf = new LanguagePesistence(getBaseContext()); 
lf.setLanguage("eng"); 

編輯:看到更多這裏:http://mobgeek.com.br/blog/apps-android-multi-idiomas

值烯

<string name="toast_network">Network not avaliable</string> 
<string name="toast_router_fail">Route not created!</string> 
<string name="toast_router_create">Wait!</string> 

值-PT

<string name="toast_network">Sem conexão com internet</string> 
<string name="toast_router_fail">Não foi possivel criar uma rota!</string> 
<string name="toast_router_create">Aguarde!</string> 

被修改部分2:

下面的代碼是在運行時改變t他的語言設置,如果你 有一個選項,選擇一種語言,因此代碼傳播到其 應用選擇的語言

Locale locale = new Locale(languageToLoad); 
      Locale.setDefault(locale); 
      Configuration config = new Configuration(); 
      config.locale = locale; 
      Resources res = this._context.getResources(); 
      res.updateConfiguration(config, res.getDisplayMetrics()); 

採取的微調選擇的語言和更改系統配置使用此

language.setOnItemSelectedListener(new OnItemSelectedListener() { 

     @Override 
     public void onItemSelected(AdapterView<?> parent, View view,int position, long id){ 
      //get language selected example: eng or esp or fr 
      LanguagePesistence lf = new LanguagePesistence(getBaseContext()); 
      lf.setLanguage("eng"); 

     } 

     @Override 
     public void onNothingSelected(AdapterView<?> arg0) { 

     } 
    }); 
+0

是否需要爲這些語言創建任何xml文件 – user3736518

+0

以及在哪裏使用此代碼LanguagePesistence lf = new LanguagePesistence(getBaseContext()); lf.setLanguage(「eng」); – user3736518

+0

@ user3736518,在您的語言轉換器中旋轉,我將添加更多信息! –