在android中实现国际化

时间:2014-07-22 03:47:19

标签: android android-layout android-intent android-activity android-fragments

我创建了一个登录页面,其中包含用户名密码登录按钮和更改语言选项(下拉列表包含所需语言)。

登录页面

enter image description here

enter image description here

我的问题是如何将国际化应用到所有页面。如果点击法语,则应该将其应用于登录页面以及登录后的下一页。请帮助..

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", 
                           "androidexample84@gmail.com");

                        // 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);
    }
}

1 个答案:

答案 0 :(得分: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

values-en

 <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部分:

  

以下代码是在运行时更改语言设置   有一个选择语言的选项,以便代码传播到它   应用程序选择的语言

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) {

        }
    });