Android基础——国际化

国际化是什么?

国际化指的是当Android系统切换语言时,相关设置也随之改变,以适应不同的国家地区

布局国际化

修改activity_main.xml,创建三个按钮,从左到右为123

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/activity_main"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <Button
        android:id="@+id/tv1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="1" />

    <Button
        android:id="@+id/tv2"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_toRightOf="@id/tv1"
        android:text="2" />

    <Button
        android:id="@+id/tv3"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_toRightOf="@id/tv2"
        android:text="3" />
</RelativeLayout>

效果如下图
在这里插入图片描述
然而有些国家的文字是从右往左读的,当调整系统语言后,app内的控件也应该随之变化,在AS中可通过如下图方式预览,但在运行时须在manifest文件下的<application>标签添加如下属性

android:supportsRtl="true"

按道理应该从右往左为123,但2和3哪去了?因为2和3设置了android:layout_toRightOf="@id/tv1",所以调整后2和3仍在其右边,但溢出屏幕导致看不到
在这里插入图片描述
为保证从右往左情况下的正确布局,需要将layout_toRightOf换成layout_toEndOf(同理所有left属性都要换成start属性),如下为正常情况
在这里插入图片描述

自定义字符串国际化

当改变系统语言时,app的语言也要随着改变,在res-values-strings.xml创建字符串"str_hello"

<?xml version="1.0" encoding="utf-8"?>
<resources>
    <string name="app_name">demo0</string>
    <string name="str_hello">hello</string>
</resources>

在activity对其引用

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/activity_main"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerInParent="true"
        android:text="@string/str_hello" />
</RelativeLayout>

strings.xml下默认存放英语,如果要存放别的语言,我们应该另外创建strings.xml(右键values-New-Values Resource file)
在这里插入图片描述
随后选择语种(可按键搜索)和地区
在这里插入图片描述
这时会生成同名带后缀的strings.xml,我们将不带后缀的默认strings.xml里的属性替换成别的语言
在这里插入图片描述
这样当系统切换语言时就会自动引用并切换到对应的语言

在这里插入图片描述
在这里插入图片描述

时间日期国际化

有些国家的阿拉伯数字写法不一样(如阿拉伯语、波斯语),SimpleDateFormat第二个参数也可自行指定国家,format之后获取的是字符串

Calendar calendar = Calendar.getInstance();
SimpleDateFormat sf = new SimpleDateFormat("dd/MM/yyyy HH:mm", Locale.getDefault());
String dateTime = sf.format(calendar.getTime());

数字国际化

同理,也可对单个数字国际化

int i = 1;
DecimalFormat decimalFormat = new DecimalFormat("#");
String num = decimalFormat.format(i);

将字符串转回数字

int i = Integer.parseInt(num);
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值