Thiru Thiru - 1 year ago 72
Android Question

localization doesn't work in my app

enter image description here
I'm using Localization to change one language to another.its work almost in my app.but in first Frament doesn't change the language.another fragments are changed the language.especially button name cannot be change.how to change it.i give my code below.

enter image description here

In fragment activity :

package com.moqawalat.introlang1;

import android.content.Intent;
import android.content.SharedPreferences;
import android.content.res.Configuration;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.view.ViewCompat;
import android.support.v4.view.ViewPager;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.text.Html;
import android.view.View;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.moqawalat.introlang1.Fragment.FragoneFragment;
import com.moqawalat.introlang1.Fragment.FragthreeFragment;
import com.moqawalat.introlang1.Fragment.FragtwoFragment;
import com.moqawalat.introlang1.Utility.JSONParser;
import com.moqawalat.introlang1.Utility.PrefManager;

import org.json.JSONObject;

import java.util.Locale;

public class InformativePageActivity extends AppCompatActivity {

ViewPager vpager;
private LinearLayout dotsLayout;
private TextView[] dots;
private Button btnSkip, btnNext;
private PrefManager prefManager;

private JSONParser jsonparser = new JSONParser();
private TextView tv,tv1,countrytxt,languagetxt;

String a,b,c,getcountry,getlanguage;
private JSONObject jsonobject = null;
SharedPreferences pref;

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);

setContentView(R.layout.activity_informativepage);


btnNext = (Button) findViewById(R.id.btn_next);
btnSkip = (Button) findViewById(R.id.btn_skip);

pref = getSharedPreferences("CountryPref",MODE_PRIVATE);

getcountry = pref.getString("country","");
getlanguage = pref.getString("language", "");

if(getlanguage.equalsIgnoreCase("en")){
Locale locale = new Locale(getlanguage);
Locale.setDefault(locale);
Configuration config = new Configuration();
config.locale = locale;
getBaseContext().getResources().updateConfiguration(config,getBaseContext().getResources().getDisplayMetrics());

SharedPreferences sp = getSharedPreferences("pref",MODE_PRIVATE);
SharedPreferences.Editor edit = sp.edit();
edit.putString("language", getlanguage);
edit.commit();
}
else if(getlanguage.equalsIgnoreCase("ar")){
Locale locale = new Locale(getlanguage);
Locale.setDefault(locale);
Configuration config = new Configuration();
config.locale = locale;
getBaseContext().getResources().updateConfiguration(config,getBaseContext().getResources().getDisplayMetrics());

SharedPreferences sp = getSharedPreferences("pref",MODE_PRIVATE);
SharedPreferences.Editor edit = sp.edit();
edit.putString("language", getlanguage);
edit.commit();
}

prefManager = new PrefManager(this);
if (!prefManager.isFirstTimeLaunch()) {
launchHomeScreen();
finish();
}


vpager = (ViewPager) findViewById(R.id.vPager);
dotsLayout = (LinearLayout) findViewById(R.id.layoutDots);
vpager.setAdapter(new setViewadapter(getSupportFragmentManager()));
vpager.addOnPageChangeListener(viewPagerPageChangeListener);
addBottomDots(0);

btnSkip.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
launchHomeScreen();
}
});

btnNext.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
// checking for last page
// if last page home screen will be launched
int current = getItem(+1);
if (current < 3) {
// move to next screen
vpager.setCurrentItem(current);
} else {
launchHomeScreen();
}
}
});

}


private int getItem(int i) {
return vpager.getCurrentItem() + i;
}


public class setViewadapter extends FragmentPagerAdapter {
public setViewadapter(FragmentManager fm) {
super(fm);
}

@Override
public Fragment getItem(int position) {
if (position == 0) {
return new FragoneFragment();
} else if (position == 1) {
return new FragtwoFragment();
} else if (position == 2) {
return new FragthreeFragment();
}
return new FragthreeFragment();


}

@Override
public int getCount() {
return 3;
}
}

private void launchHomeScreen() {
prefManager.setFirstTimeLaunch(false);
startActivity(new Intent(InformativePageActivity.this, SecondActivity.class));
finish();
}


private void addBottomDots(int currentPage) {
dots = new TextView[3];

int[] colorsActive = getResources().getIntArray(R.array.dot_act_arr);
int[] colorsInactive = getResources().getIntArray(R.array.dot_inact_arr);

dotsLayout.removeAllViews();
for (int i = 0; i < dots.length; i++) {
dots[i] = new TextView(this);
dots[i].setText(Html.fromHtml("&#8226;"));
dots[i].setTextSize(35);
dots[i].setTextColor(colorsInactive[currentPage]);
dotsLayout.addView(dots[i]);
}

if (dots.length > 0)
dots[currentPage].setTextColor(colorsActive[currentPage]);
}


ViewPager.OnPageChangeListener viewPagerPageChangeListener = new ViewPager.OnPageChangeListener() {

@Override
public void onPageSelected(int position) {
addBottomDots(position);

// changing the next button text 'NEXT' / 'GOT IT'
if (position == 3 - 1) {
// last page. make button text to GOT IT
btnNext.setText(getString(R.string.start));
btnSkip.setVisibility(View.GONE);

} else {
// still pages are left
btnNext.setText(getString(R.string.next));
btnSkip.setVisibility(View.VISIBLE);
}
}

@Override
public void onPageScrolled(int arg0, float arg1, int arg2) {

}

@Override
public void onPageScrollStateChanged(int arg0) {

}
};

@Override
public void onBackPressed() {
if (getFragmentManager().getBackStackEntryCount() > 0) {
getFragmentManager().popBackStack();
} else {
super.onBackPressed();
}
}

@Override
public void onResume(){
super.onResume();

}

}


Fragmentone:

package com.moqawalat.introlang1.Fragment;

import android.content.SharedPreferences;
import android.content.res.Configuration;
import android.content.res.Resources;
import android.graphics.PorterDuff;
import android.graphics.Typeface;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.squareup.picasso.Picasso;
import com.moqawalat.introlang1.Utility.JSONParser;
import com.moqawalat.introlang1.R;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.Locale;

import static android.content.Context.MODE_PRIVATE;

/**
* Created by ewall-07 on 3/12/16.
*/
public class FragoneFragment extends Fragment {


private JSONParser jsonparser = new JSONParser();
private TextView tv, tv1, countrytxt, languagetxt;

String a, b, c, getcountry, getlanguage;
private JSONObject jsonobject = null;
SharedPreferences pref;

@Nullable
@Override
public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {

// View v = inflater.inflate(R.layout.fragment_fragone,container,false);


View v = inflater.inflate(R.layout.fragment_fragone, container, false);
tv = (TextView) v.findViewById(R.id.text_tv);
tv1 = (TextView) v.findViewById(R.id.text_tv1);
countrytxt = (TextView) v.findViewById(R.id.country1);
languagetxt = (TextView) v.findViewById(R.id.language1);

pref = this.getActivity().getSharedPreferences("CountryPref", MODE_PRIVATE);

getcountry = pref.getString("country", "");
getlanguage = pref.getString("language", "");


if (getlanguage.equalsIgnoreCase("en") && getcountry.equalsIgnoreCase("en")) {
Locale locale = new Locale(getlanguage);
Locale.setDefault(locale);
Configuration config = new Configuration();
config.locale = locale;
getActivity().getResources().updateConfiguration(config, this.getActivity().getResources().getDisplayMetrics());

SharedPreferences sp = this.getActivity().getSharedPreferences("pref", MODE_PRIVATE);
SharedPreferences.Editor edit = sp.edit();
edit.putString("language", getlanguage);
edit.commit();

countrytxt.setText("Country : " + getlanguage);
new retrievedata_en().execute();
}
else if (getlanguage.equalsIgnoreCase("ar") && getcountry.equalsIgnoreCase("ar")) {
Locale locale = new Locale(getlanguage);

Locale.setDefault(locale);
Configuration config = new Configuration();
config.locale = locale;
getActivity().getResources().updateConfiguration(config, this.getActivity().getResources().getDisplayMetrics());

SharedPreferences sp = this.getActivity().getSharedPreferences("pref", MODE_PRIVATE);
SharedPreferences.Editor edit = sp.edit();
edit.putString("language", getlanguage);
edit.commit();

countrytxt.setText("Country : " + getlanguage);
new retrievedata_ar().execute();
}


return v;




/*

//it help us to change the font style...
Typeface type = Typeface.createFromAsset(getActivity().getAssets(),"DroidSerif-Regular.ttf");
TextView tv1 = (TextView) v.findViewById(R.id.text_tv1);
tv1.setTypeface(type);*/


}

class retrievedata_en extends AsyncTask<String, String, String> {



@Override
protected String doInBackground(String... strings) {

jsonobject = jsonparser.makeHttpRequest("http://www.json-generator.com/api/json/get/cegNjwgBTS?indent=2");

Log.d("app data", jsonobject.toString());

try {

a = jsonobject.getString("name");
b = jsonobject.getString("data");
c = jsonobject.getString("image_url");

} catch (JSONException e) {
e.printStackTrace();
}
return a;
}

protected void onPostExecute(String a) {
tv.setText(a);
tv1.setText(b);

ImageView image = (ImageView) getActivity().findViewById(R.id.image_one);
Picasso.with(getActivity()).load(c).error(R.drawable.error).placeholder(R.drawable.progress_aniamtion).noFade().into(image);
}
}


class retrievedata_ar extends AsyncTask<String, String, String> {

@Override
protected String doInBackground(String... strings) {

jsonobject = jsonparser.makeHttpRequest("http://www.json-generator.com/api/json/get/cgiIKnDVYO?indent=2");

Log.d("app data", jsonobject.toString());

try {

a = jsonobject.getString("name_ar");
b = jsonobject.getString("data_ar");
c = jsonobject.getString("image_url");

} catch (JSONException e) {
e.printStackTrace();
}
return a;
}

protected void onPostExecute(String a) {
tv.setText(a);
tv1.setText(b);

ImageView image = (ImageView) getActivity().findViewById(R.id.image_one);
Picasso.with(getActivity()).load(c).error(R.drawable.error).placeholder(R.drawable.progress_aniamtion).noFade().into(image);
}
}
}


activity_main :

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/activity_main"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
tools:context="com.moqawalat.lang.MainActivity">

<TextView
android:id="@+id/text"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:gravity="center"
android:textSize="30sp"
android:text="Shared Preferences"
android:layout_centerHorizontal="true"
/>

<Button
android:layout_width="200sp"
android:layout_height="wrap_content"
android:layout_centerVertical="true"
android:layout_centerHorizontal="true"
android:text="Add data"
android:id="@+id/add"

/>

<Button
android:layout_width="200sp"
android:layout_height="wrap_content"
android:layout_centerVertical="true"
android:layout_centerHorizontal="true"
android:layout_below="@+id/add"
android:text="view data"
android:id="@+id/view"
/>
</RelativeLayout>


activity_infragment:

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/liner_info"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#4caad4"
android:layoutDirection="locale"

tools:context=".InformativePageActivity">


<android.support.v4.view.ViewPager
android:id="@+id/vPager"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="@+id/btn_skip"
android:layout_above="@+id/btn_next"
android:layout_marginBottom="15dp"></android.support.v4.view.ViewPager>


<LinearLayout
android:id="@+id/layoutDots"
android:layout_width="match_parent"
android:layout_height="@dimen/layout_dots"
android:gravity="center"
android:orientation="horizontal"
android:layout_alignParentLeft="true"
android:layout_centerVertical="true"
android:layout_alignParentStart="false"></LinearLayout>


<Button

android:id="@+id/btn_skip"
android:layout_width="wrap_content"
android:layout_height="wrap_content"

android:layout_alignParentBottom="false"
android:layout_alignParentLeft="false"
android:layout_alignParentRight="true"
android:layout_alignParentTop="true"
android:background="@null"

android:text="@string/skip"
android:textAllCaps="false"
android:textColor="@android:color/white"
android:textSize="@dimen/btn_text_skip"
android:textStyle="bold" />


<Button
android:id="@+id/btn_next"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_centerHorizontal="true"
android:background="@drawable/drawable_check_out_button_bg"
android:paddingLeft="@dimen/padding_left"
android:paddingRight="@dimen/padding_right"
android:text="@string/next"
android:textColor="@android:color/white"
android:textSize="@dimen/btn_text_next"
android:textStyle="bold"
android:layout_marginBottom="15dp" />

</RelativeLayout>


add_fragment.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_width="match_parent"
android:layout_height="match_parent">

<EditText
android:layout_width="200sp"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:id="@+id/country"
android:hint="country"
/>

<EditText
android:layout_width="200sp"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:id="@+id/language"
android:hint="language"
/>

<Button
android:layout_width="200sp"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:id="@+id/savebtn"
android:text="save"
/>

</LinearLayout>

fragmentone.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/linear_frag_one"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#4caad4"
android:orientation="vertical"
android:weightSum="10"

>

<LinearLayout
android:layout_width="fill_parent"
android:layout_height="0dp"
android:layout_gravity="center_horizontal"
android:layout_weight="5.15"
android:gravity="center"
android:orientation="vertical">


<ImageView
android:id="@+id/image_one"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:layout_gravity="center"
android:foregroundGravity="center"
android:layout_marginTop="25dp"
android:contentDescription="@null" />

</LinearLayout>

<LinearLayout
android:layout_width="fill_parent"
android:layout_height="0dp"
android:layout_marginTop="45dp"
android:layout_weight="5"
android:orientation="vertical">



<TextView
android:id="@+id/text_tv"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:layout_marginTop="30dp"
android:gravity="center"

android:textColor="#ffffff"
android:textSize="@dimen/font_size_main"
android:textStyle="bold" />


<TextView
android:id="@+id/country1"
android:layout_width="1dp"
android:layout_height="1dp"
android:layout_gravity="center"

android:gravity="center"


android:textStyle="bold" />

<TextView
android:id="@+id/language1"
android:layout_width="1dp"
android:layout_height="1dp"
android:layout_gravity="center"

android:gravity="center"


android:textStyle="bold" />



<TextView

android:id="@+id/text_tv1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:layout_marginTop="5dp"
android:gravity="center"
android:paddingLeft="@dimen/padding_left"
android:paddingRight="@dimen/padding_left"
android:textColor="#ffffff"
android:textSize="@dimen/font_size_sub"
/>
</LinearLayout>
</LinearLayout>


values/strings.xml:

<?xml version="1.0" encoding="utf-8"?>
<resources>

<string name="app_name">Introlang1</string>

<string name="next">Continue</string>
<string name="skip">Skip</string>
<string name="start">GOT IT</string>

<string name="desc">your desc goes here</string>

<string name="file_Save">file_save</string>
<string name="language">language</string>


</resources>


values-ar/strings.xml:

<?xml version="1.0" encoding="utf-8"?>
<resources>

<string name="app_name">Introlang1</string>
<string name="next">استمر</string>
<string name="skip">تخطى</string>
<string name="start">فهمتك</string>
</resources>


I need to change next,skip button names into Arabic on first fragment.how can i change?.

Answer Source

Language Changes can we done two way:

  • Either setLocal and restart your activity.

  • Override onConfigChange method in ur current activity.

In your code I thought you are not restarting your activity so you have to override onConfigChange method in ur current activity.

I had same Issue , so I done this ways, Hope help you !

Update your configuration:

private void updateConfig() {

   getBaseContext().getResources().updateConfiguration(config,
            getBaseContext().getResources().getDisplayMetrics());

    //call this method after updateConfiguration
    onConfigurationChanged(config);
  }

In OnconfigurationChanged:

     @Override
        public void onConfigurationChanged(Configuration newConfig) {

          Log.i(TAG, "onConfigurationChanged invoked !");


 if(AppPreference.getInstance(getApplicationContext()).getAppLocale().equalsIgnoeCase(newConfig.locale.getLanguage())) {
          Log.i(TAG, "proceeding with app preference language");
          super.onConfigurationChanged(newConfig);
          refreshAllView();
      }
      Log.i(TAG, "onConfigurationChanged exit !");
    }

Write your own refreshView method inside fragment and call that method from fragment object. as like:

public void refreshAllView(){
HomeFragment homeFragment = (HomeFragment) mAdapter.instantiateItem(mViewPager, 0);
         if (homeFragment != null) {
            homeFragment.refreshView();
        }
}


//These RefreshView method should be inside your fragment
{
///......

public void refreshView() {
        //Set text again into textView,button,etc from string resource

        setTextInTextView(mTextBusTitle, R.string.lb_buses);
        setTextInTextView(mTextTrainTitle, R.string.lb_trains);
        setTextInTextView(mTextHotelTitle, R.string.lb_budget_hotel);
        setTextInTextView(mTextCheckPnr, R.string.lb_check_pnr);
        setTextInTextView(mTextRunningStatus, R.string.lb_train_running_status);
        setTextInTextView(mTextReferEarn, R.string.lb_refer_earn);
        setTextInTextView(mTextOfferTitle, R.string.lb_offers_discounts);

    }

    private void setTextInTextView(TextView textView, int resId) {
        if (textView != null) {
            textView.setText(resId);
        }

    }
}

In Manifest file add below line inside activity declaration

android:configChanges="locale"
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download