Android Studio实现国际化完整步骤
在项目res目录下,为每种目标语言创建对应的资源文件夹。操作路径:右键点击res→New→Android Resource Directory,在弹出窗口中:
values(用于文本资源);zh、fr、es);values-zh表示简体中文,values-fr表示法语)。在每个新建的values-<language>文件夹中,创建或编辑strings.xml文件,添加对应语言的翻译字符串。关键要求:所有语言版本的strings.xml中,name属性必须与默认语言(通常是values/strings.xml)中的name完全一致,仅修改value值。
示例:
values/strings.xml):<resources>
<string name="app_name">My Application</string>
<string name="welcome_message">Welcome to My App!</string>
</resources>
values-fr/strings.xml):<resources>
<string name="app_name">Mon Application</string>
<string name="welcome_message">Bienvenue dans mon application !</string>
</resources>
values-zh/strings.xml):<resources>
<string name="app_name">我的应用</string>
<string name="welcome_message">欢迎使用我的应用!</string>
</resources>
布局文件:通过@string/<resource_name>引用字符串,避免硬编码。例如:
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/welcome_message" />
Java/Kotlin代码:使用getString(R.string.<resource_name>)获取当前语言对应的字符串。例如:
// Java
TextView textView = findViewById(R.id.welcomeTextView);
textView.setText(getString(R.string.welcome_message));
// Kotlin
val textView = findViewById<TextView>(R.id.welcomeTextView)
textView.text = getString(R.string.welcome_message)
为验证多语言支持是否生效,需更改设备/模拟器的系统语言:
values/strings.xml是默认语言文件,若用户设备语言未匹配任何自定义文件夹,将使用此文件中的字符串。drawable-<language>(如drawable-fr)文件夹,放入对应语言的资源,保持文件名一致。免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。