android 国际化 中英文语言切换

本文介绍了一个简单的项目国际化过程,通过创建不同语言的strings.xml资源文件实现界面文本的切换。包括如何在Android项目中创建多语言资源包,以及如何在代码中动态更新语言设置。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

最近工作中突然要求要项目进行国际化,之前没遇到过。但是也很简单呀,只需要把添加一个相应语言的的strings.xml的资源文件就好了

创建values
在这里插入图片描述这里准备创建资源

在这里插入图片描述
点击ok 一个英文的values包就创好了

接下里 我们需要在新建的values中创建string.xml 文件 并与默认values包中的string保持一致

在这里插入图片描述
xml布局

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity">

    <Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="中文"
        android:id="@+id/china"/>

    <Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="英文"
        android:id="@+id/english"
        android:layout_marginTop="40dp"/>

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
         android:layout_centerInParent="true"
         android:text="@string/login"
        android:id="@+id/tv"/>

</RelativeLayout>

Activity中

 @Override
    protected void onResume() {
        super.onResume();
        tv.setText(R.string.login);
    }
    
 @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.china:
                updateActivity("zh");
                break;
            case R.id.english:
                updateActivity("en");
                break;
        }
    }

    public void updateActivity(String sta){
        Locale myLocale = new Locale(sta);
        Resources res = getResources();// 获得res资源对象
        DisplayMetrics dm = res.getDisplayMetrics();// 获得屏幕参数:主要是分辨率,像素等。
        Configuration conf = res.getConfiguration();// 获得设置对象
        conf.locale = myLocale;// 简体中文
        res.updateConfiguration(conf, dm);
        Intent intent = new Intent(MainActivity.this,MainActivity.class);
        startActivity(intent);
    }

当资源的语言改变时,要重新调用tv.setText()方法界面才会生效

当前Activity中我用的模式是singTop 当跳转自身时会执行onPause–onNewInstanse–onResume 所以我就将tv.setText() 中写到了 onResume中

评论 6
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值