推荐新闻
App内切换语言
发布者:深蓝互联
发布时间:2019-12-31
点击:

先上示例图:

 

代码实现:

布局文件(Data-Binding模式),很简单就是两行文字

复制代码
<?xml version="1.0" encoding="utf-8"?>
<layout xmlns:android="http://schemas.android.com/apk/res/android">

    <RelativeLayout xmlns:tools="http://schemas.android.com/tools"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        tools:context="com.tnnowu.android.switchlanguage.MainActivity">

        <TextView
            android:id="@+id/titleTextView"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_centerInParent="true"
            android:text="@string/title"
            android:textSize="30sp"
            android:textStyle="bold" />

        <TextView
            android:id="@+id/descTextView"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_below="@+id/titleTextView"
            android:layout_centerHorizontal="true"
            android:layout_marginTop="10dp"
            android:text="@string/desc"
            android:textSize="20sp" />

    </RelativeLayout>

</layout>
复制代码

 

从实例中我们可以看到右上角是有Menu

复制代码
<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    tools:context=".MainActivity">

    <item
        android:id="@+id/language_english"
        android:orderInCategory="100"
        android:title="@string/menu_english" />
    <item
        android:id="@+id/language_simplified_chinese"
        android:orderInCategory="100"
        android:title="@string/menu_simplified_chinese" />
    <item
        android:id="@+id/language_turkish"
        android:orderInCategory="100"
        android:title="@string/menu_turkish" />
    <item
        android:id="@+id/language_japanese"
        android:orderInCategory="100"
        android:title="@string/menu_japanese" />

</menu>
复制代码

(既然是多语言,所以就要有N个strings)

,本案例我创建了4种语言。

 

好的,Menu的布局写完了,接下来就是实现Menu功能,记住实现Menu就两套代码,一个 onCreateOptionsMenu , 另一个是 onOptionsItemSelected 。

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    getMenuInflater().inflate(R.menu.menu, menu);
    return true;
}

复制代码
@Override
public boolean onOptionsItemSelected(MenuItem item) {
    int id = item.getItemId();
    if (id == R.id.language_english) {
        updateViews("en");
    } else if (id == R.id.language_simplified_chinese) {
        updateViews("zh");
    } else if (id == R.id.language_turkish) {
        updateViews("tr");
    } else if (id == R.id.language_japanese) {
        updateViews("ja");
    }
    return super.onOptionsItemSelected(item);
}
复制代码

 

在这里,可以看到,我们自定义一个 updateViews() 方法,用来实现切换预言时界面的改变

复制代码
private void updateViews(String languageCode) {
    Context context = LocaleHelper.setLocale(this, languageCode);
    Resources resources = context.getResources();

    mBinding.titleTextView.setText(resources.getString(R.string.title));
    mBinding.descTextView.setText(resources.getString(R.string.desc));

    setTitle(resources.getString(R.string.toolbar_title));
}
复制代码

 

公布一个 语言判断的类 LocaleHelper

复制代码
public class LocaleHelper {

    private static final String SELECTED_LANGUAGE = "Locale.Helper.Selected.Language";

    public static Context onAttach(Context context) {
        String lang = getPersistedData(context, Locale.getDefault().getLanguage());
        return setLocale(context, lang);
    }

    public static Context onAttach(Context context, String defaultLanguage) {
        String lang = getPersistedData(context, defaultLanguage);
        return setLocale(context, lang);
    }

    public static String getLanguage(Context context) {
        return getPersistedData(context, Locale.getDefault().getLanguage());
    }

    public static Context setLocale(Context context, String language) {
        persist(context, language);

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
            return updateResources(context, language);
        }

        return updateResourcesLegacy(context, language);
    }

    private static String getPersistedData(Context context, String defaultLanguage) {
        SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(context);
        return preferences.getString(SELECTED_LANGUAGE, defaultLanguage);
    }

    private static void persist(Context context, String language) {
        SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(context);
        SharedPreferences.Editor editor = preferences.edit();

        editor.putString(SELECTED_LANGUAGE, language);
        editor.apply();
    }

    @TargetApi(Build.VERSION_CODES.N)
    private static Context updateResources(Context context, String language) {
        Locale locale = new Locale(language);
        Locale.setDefault(locale);

        Configuration configuration = context.getResources().getConfiguration();
        configuration.setLocale(locale);

        return context.createConfigurationContext(configuration);
    }

    @SuppressWarnings("deprecation")
    private static Context updateResourcesLegacy(Context context, String language) {
        Locale locale = new Locale(language);
        Locale.setDefault(locale);

        Resources resources = context.getResources();

        Configuration configuration = resources.getConfiguration();
        configuration.locale = locale;

        resources.updateConfiguration(configuration, resources.getDisplayMetrics());

        return context;
    }
}
复制代码

 

最后还要做的操作就是,自定义一个Application类,用来设定App的默认语言(当然了,要将这个Application应用到Manifest中)

复制代码
public class BaseApplication extends Application {

    @Override
    protected void attachBaseContext(Context base) {
        super.attachBaseContext(LocaleHelper.onAttach(base, "en"));
    }

}
复制代码

本案例实现App内语言切换代码量不大,通俗易懂,无垃圾代码。

 

深蓝互联成立于2013年,是一家物联网硬件开发及软件应用服务商,获得多次获得国家高新技术企业资质的企业。深蓝互联专注软硬件技术开发的专业性技术公司。我们从事软硬件开发十年,擅长SaaS 平台开发、APP小程序开发、软硬件结合开发,在视觉识别处理、数据架构、云计算、多线程高并发和集群、数据安全加密和防护方便有很深的技术积累。

 

我们拥有专业优秀的设计和技术团队,以极具创意的 UI 设计、精湛卓越的开发技术,专业的网络策划团队。公司多年来投入打造物联网SaaS平台,集成了公司研发的多款智能物联网终端(智能鲜米机、生鲜售货机、自助洗车机、小区电瓶车充电系统等)。

 

公司一直坚持以研发为导向,打造软硬件结合的物联网平台系统。将一直坚持提高开发的技术实力更好的为我们的客户服务!

 

文章来自深蓝互联http://www.szdbi.com/webxt/416.html转载请注明出处!

关注深蓝互联公众号
Copyright © 2013-2024 深蓝互联 版权所有