RTL не работает после перехода на AndroidX - PullRequest
0 голосов
/ 17 апреля 2020

Я недавно перенес свое приложение на использование androidx. Я смог программно переключить свой язык, но после перехода на AndroidX теперь он не поддерживает программную локализацию приложений. он отлично работает, если я поменяю язык моего android телефона на арабский c, в этом случае весь текст автоматически конвертируется в арабский c, а также приложение начинает отображаться в RTL, но когда я пытаюсь сделать это программно это не работает.

Извините за плохой английский sh.

ОБНОВЛЕНИЕ

apply plugin: 'com.android.application'


android {
    compileSdkVersion 28
    buildToolsVersion '28.0.3'
    packagingOptions {
        exclude 'META-INF/proguard/androidx-annotations.pro'
    }
    defaultConfig {
        applicationId "jadoontechnologies.dealmart"
        minSdkVersion 19
        targetSdkVersion 28
        versionCode 1
        versionName "1.0"
        vectorDrawables.useSupportLibrary = true
        multiDexEnabled true

        testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
        dexOptions {
            preDexLibraries = false
        }
        lintOptions {
            checkReleaseBuilds false
            // Or, if you prefer, you can continue to check for errors in release builds,
            // but continue the build even when errors are found:
            abortOnError false
        }
    }
    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
    }
    compileOptions {
        sourceCompatibility = 1.8
        targetCompatibility = 1.8
    }
}
repositories {
    mavenCentral()
    maven {
        url "https://s3-ap-southeast-1.amazonaws.com/godel-release/godel/"
    }
}

dependencies {
    implementation fileTree(include: ['*.jar'], dir: 'libs')
    implementation 'androidx.lifecycle:lifecycle-extensions:2.2.0'
    implementation 'androidx.legacy:legacy-support-v4:1.0.0'
    androidTestImplementation('androidx.test.espresso:espresso-core:3.1.0', {
        exclude group: 'com.android.support', module: 'support-annotations'
    })
    //noinspection GradleDynamicVersion,GradleCompatible
    implementation 'androidx.appcompat:appcompat:1.1.0'
    implementation 'androidx.constraintlayout:constraintlayout:1.1.3'
    implementation 'com.google.android.material:material:1.1.0'
    implementation 'com.android.volley:volley:1.1.1'
    implementation 'com.google.code.gson:gson:2.8.5'
    //implementation 'xyz.peridy.shimmer:shimmerlayout:1.1'

    //dont change picasso version
    implementation 'com.squareup.picasso:picasso:2.5.2'

    implementation 'com.nineoldandroids:library:2.4.0'
    implementation 'com.daimajia.slider:library:1.1.5@aar'
    implementation 'com.github.bumptech.glide:glide:3.7.0'
    implementation 'de.hdodenhof:circleimageview:2.2.0'
    implementation 'com.squareup.okhttp3:okhttp:3.10.0'
    implementation 'com.squareup.retrofit2:retrofit:2.2.0'
    implementation 'com.squareup.retrofit2:converter-gson:2.2.0'
    implementation 'com.google.firebase:firebase-messaging:20.1.5'
    implementation 'com.google.firebase:firebase-core:17.3.0'
    implementation 'com.fasterxml.jackson.core:jackson-databind:2.8.5'
    implementation 'com.fasterxml.jackson.core:jackson-core:2.8.5'
    implementation 'com.fasterxml.jackson.core:jackson-annotations:2.8.5'
    implementation 'com.daimajia.swipelayout:library:1.2.0@aar'
    testImplementation 'junit:junit:4.12'
    implementation 'de.hdodenhof:circleimageview:2.2.0'
    implementation 'androidx.multidex:multidex:2.0.1'
    implementation 'br.com.simplepass:loading-button-android:1.14.0'
    implementation 'org.apache.commons:commons-lang3:3.4'
    implementation 'com.llollox:androidtoggleswitch:2.0.1'

    implementation 'com.github.florent37:materialtextfield:1.0.7'

    implementation 'com.facebook.shimmer:shimmer:0.5.0'
    //implementation 'io.supercharge:shimmerlayout:2.1.0'

    implementation 'com.koushikdutta.ion:ion:2.2.1'
    implementation files('libs/PGSDK_v1.0.jar')
    implementation 'com.github.franmontiel:LocaleChanger:0.9.2'
    implementation 'androidx.recyclerview:recyclerview:1.1.0'
    implementation 'androidx.cardview:cardview:1.0.0'
    implementation 'com.shamanland:fonticon:0.1.8'
    implementation('com.nispok:snackbar:2.11.+') {
        // exclusion is not necessary, but generally a good idea.
        exclude group: 'com.google.android', module: 'support-v4'
    }
    implementation 'com.google.guava:guava:24.1-jre'
    implementation 'org.bouncycastle:bcprov-jdk16:1.46'
    implementation 'com.razorpay:checkout:1.5.2'


    implementation 'com.shuhart.stepview:stepview:1.5.1'
    implementation 'commons-codec:commons-codec:1.10'
    implementation 'com.google.firebase:firebase-appindexing:19.1.0'
    implementation files('libs/httpmime-4.2.5-sources.jar')

}
// ADD THIS AT THE BOTTOM
apply plugin: 'com.google.gms.google-services'

LocaleHelper Class

package jadoontechnologies.dealmart;

import android.annotation.TargetApi;
import android.content.Context;
import android.content.SharedPreferences;
import android.content.res.Configuration;
import android.content.res.Resources;
import android.os.Build;
import android.preference.PreferenceManager;

import java.util.Locale;

public class LocaleHelper {
        private static final String SELECTED_LANGUAGE = "Locale.Helper.Selected.Language";

        public static Context onAttach(Context context) {
            String lang = getPersistedData(context, Locale.getDefault().getLanguage());
            return setLocale(context, lang);
        }

        public static Context onAttach(Context context, String defaultLanguage) {
            String lang = getPersistedData(context, defaultLanguage);
            return setLocale(context, lang);
        }

        public static String getLanguage(Context context) {
            return getPersistedData(context, Locale.getDefault().getLanguage());
        }

        public static Context setLocale(Context context, String language) {
            persist(context, language);

            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
                return updateResources(context, language);
            }

            return updateResourcesLegacy(context, language);
        }

        private static String getPersistedData(Context context, String defaultLanguage) {
            SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(context);
            return preferences.getString(SELECTED_LANGUAGE, defaultLanguage);
        }

        private static void persist(Context context, String language) {
            SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(context);
            SharedPreferences.Editor editor = preferences.edit();

            editor.putString(SELECTED_LANGUAGE, language);
            editor.apply();
        }



        @TargetApi(Build.VERSION_CODES.N)
        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);
        }


        private static Context updateResourcesLegacy(Context context, String language) {
            Locale locale = new Locale(language);
            Locale.setDefault(locale);

            Resources resources = context.getResources();

            Configuration configuration = resources.getConfiguration();
            configuration.locale = locale;

            resources.updateConfiguration(configuration, resources.getDisplayMetrics());

            return context;
        }


}

Основная активность где я меняю язык

private void openLanguageDialog() {
        View v = LayoutInflater.from(this).inflate(R.layout.dialog_language,null,false);
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setView(v);
        TextView lEnglish = v.findViewById(R.id.l_english);
        TextView lSpanish = v.findViewById(R.id.l_arabic);
        final AlertDialog dialog = builder.create();

        lEnglish.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                LocaleHelper.setLocale(getApplication(),"en");
                getWindow().getDecorView().setLayoutDirection(View.LAYOUT_DIRECTION_LTR);
                editor.putString("language", "english");
                editor.apply();


                recreate();
                dialog.dismiss();
            }
        });
        lSpanish.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
          LocaleHelper.setLocale(getApplication(),"ar");
                getWindow().getDecorView().setLayoutDirection(View.LAYOUT_DIRECTION_RTL);
                SharedPreferences.Editor editor = sharedPreferences.edit();

                editor.putString("language", "spanish");
                editor.apply();



                recreate();
                dialog.dismiss();
            }
        });
        dialog.show();
    }
...