相关疑难解决方法(0)

迁移到Androidx后更改语言环境不起作用

我有一个支持多种语言的旧项目。我想升级支持库和目标平台,在迁移到Androidx之前,一切正常,但现在更改语言无效!

我使用此代码更改App的默认语言环境

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);
}
Run Code Online (Sandbox Code Playgroud)

并在每个活动上通过attachBaseContext这样的覆盖调用此方法:

@Override
protected void attachBaseContext(Context newBase)
{
    SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(context);
    String language = preferences.getString(SELECTED_LANGUAGE, "fa");
    super.attachBaseContext(updateResources(newBase, language));
}
Run Code Online (Sandbox Code Playgroud)

我尝试其他方法来获取字符串,但我注意到了吗?getActivity().getBaseContext().getString工作,而getActivity().getString不是工作。即使以下代码也不起作用,并且始终app_name在默认资源string.xml中显示vlaue。

<TextView
    android:id="@+id/textView"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="@string/app_name"/>
Run Code Online (Sandbox Code Playgroud)

我在https://github.com/Freydoonk/LanguageTest中共享示例代码

getActivity()..getResources().getIdentifier行不通,总是返回0!

android android-activity android-support-library androidx

21
推荐指数
7
解决办法
1900
查看次数

UnsupportedOperationException:试图从与上下文无关的上下文中获取显示

我在实时应用程序上遇到 UnsupportedOperationException 崩溃。所有崩溃都与 Moto Android 11 设备有关。可以看出它与 onKeyUp 有某种关系。但仍然不知道如何重现或解决这个问题。任何帮助,将不胜感激。

Fatal Exception: java.lang.UnsupportedOperationException: Tried to obtain display from a Context not associated with  one. Only visual Contexts (such as Activity or one created with Context#createWindowContext) or ones created with Context#createDisplayContext are associated with displays. Other types of Contexts are typically related to background entities and may return an arbitrary display.
   at android.app.ContextImpl.getDisplay(ContextImpl.java:2580)
   at android.content.ContextWrapper.getDisplay(ContextWrapper.java:1030)
   at android.content.ContextWrapper.getDisplay(ContextWrapper.java:1030)
   at android.app.Activity.onKeyUp(Activity.java:3859)
   at android.view.KeyEvent.dispatch(KeyEvent.java:2866)
   at android.app.Activity.dispatchKeyEvent(Activity.java:4176)
   at androidx.core.app.ComponentActivity.superDispatchKeyEvent(ComponentActivity.java:122)
   at androidx.core.view.KeyEventDispatcher.dispatchKeyEvent(KeyEventDispatcher.java:84)
   at androidx.core.app.ComponentActivity.dispatchKeyEvent(ComponentActivity.java:140)
   at androidx.appcompat.app.AppCompatActivity.dispatchKeyEvent(AppCompatActivity.java:558)
   at …
Run Code Online (Sandbox Code Playgroud)

android motorola keyup

6
推荐指数
1
解决办法
387
查看次数