我正在开发一个Android应用程序,它有一个设置选项来更改语言。它工作正常,但谷歌登录按钮不会改变语言,直到我关闭应用程序并重新打开它。
这是onCreate方法的代码:
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
SharedPreferences settings = PreferenceManager.getDefaultSharedPreferences(this);
String language = "en";
if (Locale.getDefault().getLanguage().equals("es")) {
language = "es";
}
String languagePref = prefs.getString(activity.getResources().getString(R.string.settings_language_key), language);
Locale locale = new Locale(languagePref);
Locale.setDefault(locale);
Configuration config = new Configuration();
config.locale = locale;
getResources().updateConfiguration(config, getResources().getDisplayMetrics());
setContentView(start_view);
SignInButton signInButton = (SignInButton) findViewById(R.id.sign_in_button);
// Set the dimensions of the sign-in button.
if ((getResources().getConfiguration().screenLayout & Configuration.SCREENLAYOUT_SIZE_MASK) == Configuration.SCREENLAYOUT_SIZE_XLARGE) {
signInButton.setSize(SignInButton.SIZE_WIDE);
} else {
signInButton.setSize(SignInButton.SIZE_STANDARD);
}
这就是布局:
<?xml version="1.0" encoding="utf-8"?>
<android.support.v4.widget.DrawerLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
xmlns:app="http://schemas.android.com/apk/res-auto"
tools:context=".StartActivity"
android:id="@+id/drawer_layout"
style="@style/StartViewDrawerContainer">
<RelativeLayout
style="@style/StartViewParentVertical">
<!-- Some GUI elements -->
<LinearLayout
style="@style/StartViewMainContainer">
<!-- More GUI elements -->
<com.google.android.gms.common.SignInButton
android:id="@+id/sign_in_button"
style="@style/StartViewSignInButton"/>
</LinearLayout>
</RelativeLayout>
<include layout="@layout/content_main" />
<android.support.design.widget.NavigationView
android:id="@+id/nav_view"
style="@style/StartViewNavigationView"
app:headerLayout="@layout/nav_header_main"
app:menu="@menu/activity_main_drawer" />
</android.support.v4.widget.DrawerLayout>
此代码适用于每个字符串文字,但不适用于Google按钮。
有没有办法以编程方式本地化登录文字?
答案 0 :(得分:0)
最后,我已经解决了为每种语言定义文字的问题,并按照说明以编程方式设置
TextView signInText = (TextView) signInButton.getChildAt(0);
signInText.setText(getString(R.string.sign_in));
答案 1 :(得分:0)
解决方法问题:
通过使用android:text
之类的解决方法,问题是按钮的底层实现可能会随时更改,从而导致代码中断。
清洁解决方案:
对于干净的解决方案,Google建议使用creating a custom button。为了防止每次重新开始工作,我创建了一个可重复使用的自定义按钮作为一个轻量级的4KB库,您可以选择在Button本身上使用string.xml
。这将根据语言集从dependencies {
compile 'com.shobhitpuri.custombuttons:google-signin:1.0.0'
}
文件中获取正确的本地化。
第1步:将以下内容添加到您的应用模块级build.gradle文件中:
<com.shobhitpuri.custombuttons.GoogleSignInButton
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerInParent="true"
android:text="@string/google_sign_up"
app:isDarkTheme="true" />
第2步:在XML布局中,请执行以下操作:
android:text="{string}"
<强>用法强>
app:isDarkTheme="{Boolean}"
:像往常一样设置按钮上的文字。
{{1}}:在按钮的蓝色主题和白色主题之间切换。该库处理文本颜色和背景颜色的更改。它还可以处理按钮按下或按钮点击时的颜色变化。
<强>来源:
希望它有所帮助。