3

My app was almost fully complete when I realized I needed to use fragments instead of activities in order to share the same Navigation Menu across all of the screens, so now I'm in the process of making all of my activity java code work in fragments. One issue that I can't seem to figure out is the spinner that changes the language. I have the English (Default), Spanish (ES), and French (FR) strings made and translated. When someone selects Spanish on the spinner I want it to change the app's locale to Spanish (es) & make a toast that says Language changed to Spanish!, etc. In order to do this, it must restart the fragment, correct? So begin settings fragment from settings fragment so the language updates? Right now, when I select an option from the spinner I can see that I selected it on the spinner, but nothing happens. No toast, no language, no refresh of the fragment, etc. All help is very much appreciated! Thank you!! I will post code below!

package com.ezeapplications.quikflipfinal;


import android.content.Intent;
import android.content.res.Configuration;
import android.content.res.Resources;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentTransaction;
import android.util.DisplayMetrics;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.Spinner;
import android.widget.Toast;

import java.util.Locale;
import java.util.Set;


/**
 * A simple {@link Fragment} subclass.
 */
public class SettingsFragment extends Fragment implements View.OnClickListener, AdapterView.OnItemSelectedListener {

    public SettingsFragment() {
        // Required empty public constructor
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_settings, container, false);
        Button settupdatebtn = (Button) view.findViewById(R.id.setting_update_btn);
        settupdatebtn.setOnClickListener(this);

        Spinner langspinner = (Spinner) view.findViewById(R.id.settings_language_spinner);
        // Create an ArrayAdapter using the string array and a default spinner layout
        ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(getActivity(),
                R.array.lang_array, android.R.layout.simple_spinner_item);
        // Specify the layout to use when the list of choices appears
        adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
        // Apply the adapter to the spinner
        langspinner.setAdapter(adapter);
        return view;
    }

    @Override
    public void onItemSelected(AdapterView<?> parent, View view, int pos, long id) {

        Spinner langspinner = (Spinner) view.findViewById(R.id.settings_language_spinner);
        langspinner.setOnItemSelectedListener(this);

        if (pos == 1) {

            Toast.makeText(parent.getContext(),
                    "You Have Selected English!", Toast.LENGTH_SHORT)
                    .show();
            setLocale("en");
            SettingsFragment fragmenten = new SettingsFragment();
            android.support.v4.app.FragmentTransaction fragmentTransactionen =
                    getActivity().getSupportFragmentManager().beginTransaction();
            fragmentTransactionen.replace(R.id.fragment_container, fragmenten);
            fragmentTransactionen.commit();
            langspinner.setSelection(1);

        } else if (pos == 2) {

            Toast.makeText(parent.getContext(),
                    "Has Seleccionado Español!", Toast.LENGTH_SHORT)
                    .show();
            setLocale("es");
            SettingsFragment fragmentes = new SettingsFragment();
            android.support.v4.app.FragmentTransaction fragmentTransactiones =
                    getActivity().getSupportFragmentManager().beginTransaction();
            fragmentTransactiones.replace(R.id.fragment_container, fragmentes);
            fragmentTransactiones.commit();
            langspinner.setSelection(2);

        } else if (pos == 3) {

            Toast.makeText(parent.getContext(),
                    "Vous Avez Sélectionné Le Français!", Toast.LENGTH_SHORT)
                    .show();
            setLocale("fr");
            SettingsFragment fragmentfr = new SettingsFragment();
            android.support.v4.app.FragmentTransaction fragmentTransactionfr =
                    getActivity().getSupportFragmentManager().beginTransaction();
            fragmentTransactionfr.replace(R.id.fragment_container, fragmentfr);
            fragmentTransactionfr.commit();
            langspinner.setSelection(3);
        }
    }

    public void onNothingSelected(AdapterView<?> arg0) {
        // TODO Auto-generated method stub
    }


        @Override
                public void onClick (View v) {
            SettingsFragment fragment = new SettingsFragment();
            android.support.v4.app.FragmentTransaction fragmentTransaction =
                    getFragmentManager().beginTransaction();
            fragmentTransaction.replace(R.id.fragment_container,fragment);
            fragmentTransaction.commit();
            Toast.makeText(getActivity(), "Settings Updated!", Toast.LENGTH_SHORT).show();
        };

    Locale myLocale;
    public void setLocale(String lang) {
        myLocale = new Locale(lang);
        Locale.setDefault(myLocale);
        Resources res = getResources();
        DisplayMetrics dm = res.getDisplayMetrics();
        Configuration conf = res.getConfiguration();
        conf.locale = myLocale;
        res.updateConfiguration(conf, dm);
        refresh();


}

public void refresh() {
    Fragment currentFragment = getFragmentManager().findFragmentByTag("fragment_tag_String");
    FragmentTransaction fragTransaction = getFragmentManager().beginTransaction();
    fragTransaction.detach(currentFragment);
    fragTransaction.attach(currentFragment);
    fragTransaction.commit();

}

    }
Atai Ambus
  • 89
  • 1
  • 2
  • 10
CoolBeener
  • 43
  • 4

2 Answers2

0

You may just detach and attach your fragments. Then it will refresh the views and the local will be changed.

    Fragment currentFragment = getFragmentManager().findFragmentByTag("FRAGMENT");
    FragmentTransaction fragTransaction = getFragmentManager().beginTransaction();
    fragTransaction.detach(currentFragment);
    fragTransaction.attach(currentFragment);
    fragTransaction.commit();

Set fragmentTag for SettingsFragment in MainActivity where you called this fragment. (ex: OnNavigationItemSelected() method).

    FragmentManager fm = getFragmentManager();
    fm.beginTransaction().replace(R.id.content_frame, new YourSettingsFragment(),"Tag").commit();
Atai Ambus
  • 89
  • 1
  • 2
  • 10
tahsinRupam
  • 6,325
  • 1
  • 18
  • 34
0

try this:

public class SettingsFragment extends Fragment implements View.OnClickListener, AdapterView.OnItemSelectedListener {

    Spinner langspinner;

    public SettingsFragment() {
        // Required empty public constructor
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_settings, container, false);
        Button settupdatebtn = (Button) view.findViewById(R.id.setting_update_btn);
        settupdatebtn.setOnClickListener(this);

        langspinner = (Spinner) view.findViewById(R.id.settings_language_spinner);
        langspinner.setOnItemSelectedListener(this);
        // Create an ArrayAdapter using the string array and a default spinner layout
        ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(getActivity(),
                R.array.lang_array, android.R.layout.simple_spinner_item);
        // Specify the layout to use when the list of choices appears
        adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
        // Apply the adapter to the spinner
        langspinner.setAdapter(adapter);
        langspinner.setSelection(0, false);
        return view;
    }

    @Override
    public void onItemSelected(AdapterView<?> parent, View view, int pos, long id) {

        if (pos == 1) {

            Toast.makeText(parent.getContext(),
                    "You Have Selected English!", Toast.LENGTH_SHORT)
                    .show();
            setLocale("en");
            langspinner.setSelection(1);

        } else if (pos == 2) {

            Toast.makeText(parent.getContext(),
                    "Has Seleccionado Español!", Toast.LENGTH_SHORT)
                    .show();
            setLocale("es");
            langspinner.setSelection(2);

        } else if (pos == 3) {

            Toast.makeText(parent.getContext(),
                    "Vous Avez Sélectionné Le Français!", Toast.LENGTH_SHORT)
                    .show();
            setLocale("fr");
            langspinner.setSelection(3);
        }
    }

    public void onNothingSelected(AdapterView<?> arg0) {
        // TODO Auto-generated method stub
    }


    @Override
    public void onClick(View v) {
        SettingsFragment fragment = new SettingsFragment();
        android.support.v4.app.FragmentTransaction fragmentTransaction =
                getFragmentManager().beginTransaction();
        fragmentTransaction.replace(R.id.fragment_container, fragment);
        fragmentTransaction.commit();
        Toast.makeText(getActivity(), "Settings Updated!", Toast.LENGTH_SHORT).show();
    }


    Locale myLocale;

    public void setLocale(String lang) {
        myLocale = new Locale(lang);
        Locale.setDefault(myLocale);
        Resources res = getResources();
        DisplayMetrics dm = res.getDisplayMetrics();
        Configuration conf = res.getConfiguration();
        conf.locale = myLocale;
        res.updateConfiguration(conf, dm);
        refresh();


    }

    public void refresh() {
        Fragment currentFragment = getFragmentManager().findFragmentByTag("fragment_tag_String");
        FragmentTransaction fragTransaction = getFragmentManager().beginTransaction();
        fragTransaction.detach(currentFragment);
        fragTransaction.attach(currentFragment);
        fragTransaction.commit();

    }

}

Make sure when you load the SettingsFragment from your activity u add the Fragment tag

Like this;

 SettingsFragment fragmentA = new SettingsFragment();
getSupportFragmentManager().beginTransaction()
    .replace(R.id.MainFrameLayout,fragmentA,"fragment_tag_String")
    .addToBackStack(null).commit(); 
rafsanahmad007
  • 23,683
  • 6
  • 47
  • 62
  • Still doesn't work. Made some changes though. I will update code in post. – CoolBeener Feb 05 '17 at 22:57
  • I added that, and now the spinner shows the selected language, and changes it! The only issue is the fact that is is constantly making a new you have updated the language toast. as soon as one begins fading, a new one is made. Thanks!! Hope you can help! – CoolBeener Feb 06 '17 at 21:22
  • add `langspinner.setSelection(0, false);` after setting the adpater..check the edit..also if ur language loading problem is solved mark the answer as correct – rafsanahmad007 Feb 07 '17 at 16:11