Autore Topic: Cambiare lingua app sul MainDrawerFragment  (Letto 310 volte)

Offline ZioArnold

  • Nuovo arrivato
  • *
  • Post: 8
  • Respect: 0
    • Mostra profilo
  • Dispositivo Android:
    Samsug Galaxy S2 - GT 9100
  • Sistema operativo:
    Windows 10 Pro
Cambiare lingua app sul MainDrawerFragment
« il: 21 Ottobre 2015, 23:31:18 CEST »
0
CIAO RAGAZZI, COME FACCIO A CAMBIARE LA LINGUA DELL'APP DATO QUESTI FILE SORGENTI???
Nel caso di overFlowMenu sull'ActionBar la lingua cambia, perche' la classe MainActivity estende Activity. Mentre sul Fragment estende la classe Fragment, non posso cambiare la lingua anche se metto un ClickListener?

Codice (XML): [Seleziona]
<!-- A DrawerLayout is intended to be used as the top-level content view using match_parent for both width and height to consume the full space available. -->
<android.support.v4.widget.DrawerLayout xmlns:android="http://schemas.android.com/apk/res/android"
   xmlns:tools="http://schemas.android.com/tools"
   android:id="@+id/drawer_layout"
   android:layout_width="match_parent" android:layout_height="match_parent"
   tools:context=".MainActivity">

    <!-- As the main content view, the view below consumes the entire
        space available using match_parent in both dimensions. -->
    <RelativeLayout android:id="@+id/container"
       android:layout_width="match_parent"
       android:layout_height="match_parent" >
        <Button
           android:layout_width="fill_parent"
           android:layout_height="wrap_content"
           android:text="@string/La_nostra_storia"
           android:textColor="#000"
           android:id="@+id/storyButton"
           android:layout_centerHorizontal="true"
           android:background="#ffff33"
           android:layout_marginTop="5dp" />

        <Button
           android:layout_width="fill_parent"
           android:layout_height="wrap_content"
           android:text="@string/specSectionButtonId"
           android:id="@+id/specSectionButtonId"
           android:layout_below="@+id/storyButton"
           android:layout_alignLeft="@+id/storyButton"
           android:textColor="#000"
           android:background="#4169E1"
           android:layout_marginTop="5dp" />

        <Button
           android:layout_width="fill_parent"
           android:layout_height="wrap_content"
           android:text="@string/e_registry"
           android:id="@+id/e_registryId"
           android:layout_below="@+id/specSectionButtonId"
           android:layout_centerHorizontal="true"
           android:textColor="#000"
           android:background="#FF6347"
           android:layout_marginTop="5dp" />

        <Button
           android:layout_width="fill_parent"
           android:layout_height="wrap_content"
           android:text="@string/feedback"
           android:id="@+id/feedback"
           android:layout_below="@+id/e_registryId"
           android:layout_centerHorizontal="true"
           android:textColor="#000"
           android:background="#c0c0c0"
           android:layout_marginTop="5dp" />

        <Button
           android:layout_width="fill_parent"
           android:layout_height="wrap_content"
           android:text="@string/findus"
           android:textColor="#000"
           android:id="@+id/findus"
           android:layout_below="@id/feedback"
           android:layout_centerHorizontal="true"
           android:background="#ffff33"
           android:layout_marginTop="5dp" />

        <Button
           android:layout_width="fill_parent"
           android:layout_height="wrap_content"
           android:text="@string/communications_news"
           android:id="@+id/button_show_comunications"
           android:layout_below="@+id/findus"
           android:layout_centerHorizontal="true"
           android:background="#4169E1"
           android:layout_marginTop="5dp" />
    </RelativeLayout>

    <!-- The drawer is given a fixed width in dp and extends the full height of
        the container. -->
    <fragment android:id="@+id/navigation_drawer"
       android:layout_width="@dimen/navigation_drawer_width" android:layout_height="match_parent"
       android:layout_gravity="start"
       android:name="com.example.arnold.itsosgadda.NavigationDrawerFragment"
       tools:layout="@layout/drawer_main_navitagion_drawer" />


</android.support.v4.widget.DrawerLayout>

Codice (XML): [Seleziona]
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
   xmlns:tools="http://schemas.android.com/tools"
   android:layout_width="match_parent"
   android:layout_height="match_parent"
   android:paddingLeft="@dimen/activity_horizontal_margin"
   android:paddingRight="@dimen/activity_horizontal_margin"
   android:paddingTop="@dimen/activity_vertical_margin"
   android:paddingBottom="@dimen/activity_vertical_margin"
   tools:context="com.example.arnold.itsosgadda.MainActivity$PlaceholderFragment">

    <TextView android:id="@+id/section_label"
       android:layout_width="wrap_content"
       android:layout_height="wrap_content"/>

</RelativeLayout>

Codice (XML): [Seleziona]
<ListView xmlns:android="http://schemas.android.com/apk/res/android"
   xmlns:tools="http://schemas.android.com/tools"
   android:layout_width="match_parent"
   android:layout_height="match_parent"
   android:choiceMode="singleChoice"
   android:divider="@android:color/transparent"
   android:dividerHeight="0dp"
   android:background="#fff"
   tools:context="com.example.arnold.itsosgadda.NavigationDrawerFragment"/>

Codice (Java): [Seleziona]
package com.example.arnold.itsosgadda;

import android.annotation.SuppressLint;
import android.app.ActionBar;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.Fragment;
import android.app.FragmentManager;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.res.Configuration;
import android.os.Bundle;
import android.support.v4.widget.DrawerLayout;
import android.text.method.LinkMovementMethod;
import android.text.util.Linkify;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewConfiguration;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;

import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.util.Locale;

import static android.view.View.OnClickListener;
import static android.view.Window.FEATURE_ACTION_BAR;
import static android.widget.Toast.LENGTH_LONG;
import static com.example.arnold.itsosgadda.NavigationDrawerFragment.NavigationDrawerCallbacks;
import static com.example.arnold.itsosgadda.R.id.about_app;
import static com.example.arnold.itsosgadda.R.id.action_english_language_selected;
import static com.example.arnold.itsosgadda.R.id.action_italian_language_selected;
import static com.example.arnold.itsosgadda.R.id.action_russian_language_selected;
import static com.example.arnold.itsosgadda.R.id.button_show_comunications;
import static com.example.arnold.itsosgadda.R.id.e_registryId;
import static com.example.arnold.itsosgadda.R.id.feedback;
import static com.example.arnold.itsosgadda.R.id.findus;
import static com.example.arnold.itsosgadda.R.id.specSectionButtonId;
import static com.example.arnold.itsosgadda.R.id.storyButton;
import static com.example.arnold.itsosgadda.R.layout.activity_main;
import static com.example.arnold.itsosgadda.R.menu.main_menu;
import static java.lang.Boolean.TYPE;

public class MainActivity extends Activity implements OnClickListener,
        NavigationDrawerCallbacks{
    private Button storyButtonMainBody, specSectButton, webRegistryButton, feedBackButton,
    findUsButton, communicationButton;
    private NavigationDrawerFragment mNavigationDrawerFragment;
    private CharSequence mTitle;

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

        storyButtonMainBody = (Button) findViewById(storyButton);
        storyButtonMainBody.setOnClickListener(this);

        specSectButton = (Button) findViewById(specSectionButtonId);
        specSectButton.setOnClickListener(this);

        webRegistryButton = (Button) findViewById(e_registryId);
        webRegistryButton.setOnClickListener(this);

        feedBackButton = (Button) findViewById(feedback);
        feedBackButton.setOnClickListener(this);

        findUsButton = (Button) findViewById(findus);
        findUsButton.setOnClickListener(this);

        communicationButton = (Button) findViewById(R.id.button_show_comunications);
        communicationButton.setOnClickListener(this);

        mNavigationDrawerFragment = (NavigationDrawerFragment)
               getFragmentManager().findFragmentById(R.id.navigation_drawer);
        mTitle = getTitle();

        // Set up the drawer.
        mNavigationDrawerFragment.setUp(
                R.id.navigation_drawer,
                (DrawerLayout) findViewById(R.id.drawer_layout));


        makeActionOverflowMenuShown();
    }

    @Override
    public void onNavigationDrawerItemSelected(int position) {
        // update the main content by replacing fragments
        FragmentManager fragmentManager = getFragmentManager();
        fragmentManager.beginTransaction()
                .replace(R.id.container, PlaceholderFragment.newInstance(position + 1))
                .commit();
    }

    public void onSectionAttached(int number) {
        switch (number) {
            case 1:
                mTitle = getString(R.string.en_lang);
                break;
            case 2:
                mTitle = getString(R.string.ru_lang);
                break;
            case 3:
                mTitle = getString(R.string.it_lang);
                break;
        }
    }

    public void restoreActionBar() {
        ActionBar actionBar = getActionBar();
        assert actionBar != null;
        //noinspection deprecation
        actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_STANDARD);
        actionBar.setDisplayShowTitleEnabled(true);
        actionBar.setTitle(mTitle);
    }

    /**
     * A placeholder fragment containing a simple view.
     */

    public static class PlaceholderFragment extends Fragment {
        /**
         * The fragment argument representing the section number for this
         * fragment.
         */

        private static final String ARG_SECTION_NUMBER = "section_number";

        /**
         * Returns a new instance of this fragment for the given section
         * number.
         */

        public static PlaceholderFragment newInstance(int sectionNumber) {
            PlaceholderFragment fragment = new PlaceholderFragment();
            Bundle args = new Bundle();
            args.putInt(ARG_SECTION_NUMBER, sectionNumber);
            fragment.setArguments(args);
            return fragment;
        }

        public PlaceholderFragment() {
        }

        @Override
        public View onCreateView(LayoutInflater inflater, ViewGroup container,
                                 Bundle savedInstanceState) {
            return inflater.inflate(R.layout.fragment_main_navitagion_drawer, container, false);
        }

        @Override
        public void onAttach(Activity activity) {
            super.onAttach(activity);

            ((MainActivity) activity).onSectionAttached(
                    getArguments().getInt(ARG_SECTION_NUMBER));
        }
    }

    private void makeActionOverflowMenuShown() {
        //devices with hardware menu button (e.g. Samsung Note) don't show action overflow menu
        try {
            ViewConfiguration config = ViewConfiguration.get(this);
            Field menuKeyField = ViewConfiguration.class.getDeclaredField("sHasPermanentMenuKey");
            if (menuKeyField != null) {
                menuKeyField.setAccessible(true);
                menuKeyField.setBoolean(config, false);
            }
        } catch (Exception e) {
            Log.d(null, e.getLocalizedMessage());
        }
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(main_menu, menu);
        return super.onCreateOptionsMenu(menu);
    }

    @Override
    public boolean onMenuOpened(int featureId, Menu menu) {
        if(featureId == FEATURE_ACTION_BAR && menu != null){
            if(menu.getClass().getSimpleName().equals("MenuBuilder")){
                try{
                    Method m = menu.getClass().getDeclaredMethod(
                            "setOptionalIconsVisible", TYPE);
                    m.setAccessible(true);
                    m.invoke(menu, true);
                }
                catch(NoSuchMethodException e){
                    Log.e("MyActivity", "onMenuOpened", e);
                }
                catch(Exception e){
                    throw new RuntimeException(e);
                }
            }
        }
        return super.onMenuOpened(featureId, menu);
    }

    @SuppressLint("SetTextI18n")
    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();
        switch (id) {
            case action_english_language_selected:
                Locale locale = new Locale("en");
                Locale.setDefault(locale);
                Configuration config = new Configuration();
                config.locale = locale;
                getBaseContext()
                        .getResources()
                        .updateConfiguration(config, getBaseContext()
                                .getResources()
                                .getDisplayMetrics());
                restartActivity();
                Toast.makeText(this, R.string.locale_lang, LENGTH_LONG).show();
                break;

            case action_russian_language_selected:
                Locale locale2 = new Locale("ru");
                Locale.setDefault(locale2);
                Configuration config2 = new Configuration();
                config2.locale = locale2;
                getBaseContext()
                        .getResources()
                        .updateConfiguration(config2, getBaseContext()
                                .getResources()
                                .getDisplayMetrics());
                restartActivity();
                Toast.makeText(this, R.string.locale_lang, LENGTH_LONG).show();
                break;

            case action_italian_language_selected:
                Locale locale3 = new Locale("it");
                Locale.setDefault(locale3);
                Configuration config3 = new Configuration();
                config3.locale = locale3;
                getBaseContext()
                        .getResources()
                        .updateConfiguration(config3, getBaseContext()
                                .getResources()
                                .getDisplayMetrics());
                restartActivity();
                Toast.makeText(this, R.string.locale_lang, LENGTH_LONG).show();
                break;
            case about_app:
                AlertDialog.Builder builder = new AlertDialog.Builder(this);
                builder.setIcon(R.mipmap.ic_launcher)
                        .setTitle(R.string.created_for)
                        .setMessage(R.string.to_do_list)
                        .setPositiveButton("OK", new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                dialog.dismiss();
                            }
                        })
                        .show().setCanceledOnTouchOutside(true);
                AlertDialog dialog = builder.create();
                dialog.dismiss();
                break;
            case R.id.subscribe:
                TextView tvDisplay = new TextView(this);
                final String data = "- vkontakte: https://vk.com/arnold.charyyev\n" +
                        "- facebook: https://www.facebook.com/schyzomaniac.mind\n" +
                        "- youtube: https://www.youtube.com/user/Perceus100/\n"+
                        "- gmail: vl80tk@gmail.com\n"+
                        "- yandex: arn8109@yandex.com";
                tvDisplay.setText(data);
                tvDisplay.setLinksClickable(true);
                tvDisplay.setAutoLinkMask(RESULT_OK);
                tvDisplay.setMovementMethod(LinkMovementMethod.getInstance());
                Linkify.addLinks(tvDisplay, Linkify.ALL);

                AlertDialog.Builder alert = new AlertDialog.Builder(this);
                alert.setIcon(R.mipmap.icon_subscribe_contact)
                        .setTitle(R.string.dev_contact)
                        .setView(tvDisplay)
                        .setCancelable(false)
                        .setPositiveButton("OK", new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                dialog.dismiss();
                            }
                        })
                        .show();
                AlertDialog dialogAlert = alert.create();
                dialogAlert.dismiss();
                break;

        }
        return super.onOptionsItemSelected(item);
    }

    private void restartActivity() {
        Intent intent = getIntent();
        finish();
        startActivity(intent);
    }

    private void storyButtonClicked() {
        startActivity(new Intent(getApplicationContext(), StoryActivity.class));
    }

    private void specSectButtonClicked() {
        startActivity(new Intent(getApplicationContext(), SpecStorySectionActivity.class));
    }

    private void webRegistryButtonClicked() {
        startActivity(new Intent(getApplicationContext(),WebRegistryActivity.class));
    }

    private void feedbackMailToButtonClicked() {
        startActivity(new Intent(getApplicationContext(), EmailSendingActivity.class));
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case storyButton: storyButtonClicked(); break;
            case specSectionButtonId: specSectButtonClicked(); break;
            case e_registryId: webRegistryButtonClicked(); break;
            case feedback: feedbackMailToButtonClicked(); break;
            case findus:
                AlertDialog.Builder builder = new AlertDialog.Builder(this);
                builder.setIcon(R.mipmap.ic_launcher)
                        .setTitle(R.string.created_for)
                        .setMessage(R.string.reaching_from_fornovo_FS)
                        .setPositiveButton("OK", new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                startActivity(new Intent(getApplicationContext(),
                                        MapsActivity.class));
                            }
                        })
                        .show().setCanceledOnTouchOutside(true);
                AlertDialog dialog = builder.create();
                dialog.dismiss();
                break;
            case button_show_comunications:
                AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(this);
                alertDialogBuilder.setIcon(R.mipmap.ic_launcher)
                        .setTitle(R.string.created_for)
                        .setMessage(R.string.click_ok_to_proceed)
                        .setPositiveButton("OK", new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                startActivity(new Intent(getApplicationContext(),
                                        CommunicationsActivity.class));
                            }
                        })
                        .show().setCanceledOnTouchOutside(true);
                AlertDialog alertDialog = alertDialogBuilder.create();
                alertDialog.dismiss();
                break;
        }
    }
}

Codice (Java): [Seleziona]
package com.example.arnold.itsosgadda;


import android.app.ActionBar;
import android.app.Activity;
import android.app.Fragment;
import android.content.SharedPreferences;
import android.content.res.Configuration;
import android.content.res.TypedArray;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.support.v4.app.ActionBarDrawerToggle;
import android.support.v4.widget.DrawerLayout;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ListView;

import java.util.ArrayList;

import static android.support.v4.view.GravityCompat.START;
import static com.example.arnold.itsosgadda.R.drawable.drawer_shadow;

/**
 * Fragment used for managing interactions for and presentation of a navigation drawer.
 * See the <a href="https://developer.android.com/design/patterns/navigation-drawer.html#Interaction">
 * design guidelines</a> for a complete explanation of the behaviors implemented here.
 */

public class NavigationDrawerFragment extends Fragment {

    private String[] navMenuTitles;
    private ArrayList<NavDrawerItem> navDrawerItems;
    private NavDrawerListAdapter adapter;
    private TypedArray navMenuIcons;
    /**
     * Remember the position of the selected item.
     */

    private static final String STATE_SELECTED_POSITION = "selected_navigation_drawer_position";

    /**
     * Per the design guidelines, you should show the drawer on launch until the user manually
     * expands it. This shared preference tracks this.
     */

    private static final String PREF_USER_LEARNED_DRAWER = "navigation_drawer_learned";

    /**
     * A pointer to the current callbacks instance (the Activity).
     */

    private NavigationDrawerCallbacks mCallbacks;

    /**
     * Helper component that ties the action bar to the navigation drawer.
     */

    @SuppressWarnings("deprecation")
    private ActionBarDrawerToggle mDrawerToggle;

    private DrawerLayout mDrawerLayout;
    private ListView mDrawerListView;
    private View mFragmentContainerView;

    private int mCurrentSelectedPosition = 0;
    private boolean mFromSavedInstanceState;
    private boolean mUserLearnedDrawer;

    public NavigationDrawerFragment() {
    }

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

        // Read in the flag indicating whether or not the user has demonstrated awareness of the
        // drawer. See PREF_USER_LEARNED_DRAWER for details.
        SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(getActivity());
        mUserLearnedDrawer = sp.getBoolean(PREF_USER_LEARNED_DRAWER, false);

        if (savedInstanceState != null) {
            mCurrentSelectedPosition = savedInstanceState.getInt(STATE_SELECTED_POSITION);
            mFromSavedInstanceState = true;
        }

        // Select either the default item (0) or the last selected item.
        selectItem(mCurrentSelectedPosition);
    }

    @Override
    public void onActivityCreated(Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        // Indicate that this fragment would like to influence the set of actions in the action bar.
        setHasOptionsMenu(true);
    }

    @Override
    public View onCreateView(final LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        mDrawerListView = (ListView) inflater.inflate(
                R.layout.drawer_main_navitagion_drawer, container, false);
        mDrawerListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                selectItem(position);
            }
        });


        navMenuTitles = getResources().getStringArray(R.array.nav_drawer_items);
        navMenuIcons = getResources()
                .obtainTypedArray(R.array.nav_drawer_icons);
        navDrawerItems = new ArrayList<NavDrawerItem>();
        navDrawerItems.add(new NavDrawerItem(navMenuTitles[0], navMenuIcons.getResourceId(0, -1)));
        // Find People
        navDrawerItems.add(new NavDrawerItem(navMenuTitles[1], navMenuIcons.getResourceId(1, -1)));
        // Photos
        navDrawerItems.add(new NavDrawerItem(navMenuTitles[2], navMenuIcons.getResourceId(2, -1)));

        adapter = new NavDrawerListAdapter(getActivity().getApplicationContext(),
                navDrawerItems);

        adapter = new NavDrawerListAdapter(getActivity().getApplicationContext(),
                navDrawerItems);
        mDrawerListView.setAdapter(adapter);
        /*mDrawerListView.setAdapter(new ArrayAdapter<String>(
                getActionBar().getThemedContext(),
                R.layout.list_item_activated,
                R.id.text_simple,
                new String[]{
                        getString(R.string.en_lang),
                        getString(R.string.ru_lang),
                        getString(R.string.it_lang),
                }));*/

        mDrawerListView.setItemChecked(mCurrentSelectedPosition, true);
        mDrawerListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
               
            }
        });

        return mDrawerListView;
    }

    public boolean isDrawerOpen() {
        return mDrawerLayout != null && mDrawerLayout.isDrawerOpen(mFragmentContainerView);
    }

    /**
     * Users of this fragment must call this method to set up the navigation drawer interactions.
     *
     * @param fragmentId   The android:id of this fragment in its activity's layout.
     * @param drawerLayout The DrawerLayout containing this fragment's UI.
     */

    public void setUp(int fragmentId, DrawerLayout drawerLayout) {
        mFragmentContainerView = getActivity().findViewById(fragmentId);
        mDrawerLayout = drawerLayout;

        // set a custom shadow that overlays the main content when the drawer opens
        mDrawerLayout.setDrawerShadow(drawer_shadow, START);
        // set up the drawer's list view with items and click listener

        ActionBar actionBar = getActionBar();
        actionBar.setDisplayHomeAsUpEnabled(true);
        actionBar.setHomeButtonEnabled(true);

        // ActionBarDrawerToggle ties together the the proper interactions
        // between the navigation drawer and the action bar app icon.
        //noinspection deprecation
        mDrawerToggle = new ActionBarDrawerToggle(
                getActivity(),                    /* host Activity */
                mDrawerLayout,                    /* DrawerLayout object */
                R.mipmap.ic_launcher,             /* nav drawer image to replace 'Up' caret */
                R.string.navigation_drawer_open,  /* "open drawer" description for accessibility */
                R.string.navigation_drawer_close  /* "close drawer" description for accessibility */
        ) {
            @Override
            public void onDrawerClosed(View drawerView) {
                super.onDrawerClosed(drawerView);
                if (!isAdded()) {
                    return;
                }

                getActivity().invalidateOptionsMenu(); // calls onPrepareOptionsMenu()
            }

            @Override
            public void onDrawerOpened(View drawerView) {
                super.onDrawerOpened(drawerView);
                if (!isAdded()) {
                    return;
                }

                if (!mUserLearnedDrawer) {
                    // The user manually opened the drawer; store this flag to prevent auto-showing
                    // the navigation drawer automatically in the future.
                    mUserLearnedDrawer = true;
                    SharedPreferences sp = PreferenceManager
                            .getDefaultSharedPreferences(getActivity());
                    sp.edit().putBoolean(PREF_USER_LEARNED_DRAWER, true).apply();
                }

                getActivity().invalidateOptionsMenu(); // calls onPrepareOptionsMenu()
            }
        };

        // If the user hasn't 'learned' about the drawer, open it to introduce them to the drawer,
        // per the navigation drawer design guidelines.
        if (!mUserLearnedDrawer && !mFromSavedInstanceState) {
            mDrawerLayout.openDrawer(mFragmentContainerView);
        }

        // Defer code dependent on restoration of previous instance state.
        mDrawerLayout.post(new Runnable() {
            @Override
            public void run() {
                mDrawerToggle.syncState();
            }
        });

        mDrawerLayout.setDrawerListener(mDrawerToggle);
    }

    private void selectItem(int position) {
        mCurrentSelectedPosition = position;
        if (mDrawerListView != null) {
            mDrawerListView.setItemChecked(position, true);
        }
        if (mDrawerLayout != null) {
            mDrawerLayout.closeDrawer(mFragmentContainerView);
        }
        if (mCallbacks != null) {
            mCallbacks.onNavigationDrawerItemSelected(position);
        }
    }

    @Override
    public void onAttach(Activity activity) {
        super.onAttach(activity);
        try {
            mCallbacks = (NavigationDrawerCallbacks) activity;
        } catch (ClassCastException e) {
            throw new ClassCastException("Activity must implement NavigationDrawerCallbacks.");
        }
    }

    @Override
    public void onDetach() {
        super.onDetach();
        mCallbacks = null;
    }

    @Override
    public void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
        outState.putInt(STATE_SELECTED_POSITION, mCurrentSelectedPosition);
    }

    @Override
    public void onConfigurationChanged(Configuration newConfig) {
        super.onConfigurationChanged(newConfig);
        // Forward the new configuration the drawer toggle component.
        mDrawerToggle.onConfigurationChanged(newConfig);
    }

    @Override
    public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
        // If the drawer is open, show the global app actions in the action bar. See also
        // showGlobalContextActionBar, which controls the top-left area of the action bar.
        if (mDrawerLayout != null && isDrawerOpen()) {
            inflater.inflate(R.menu.main_menu, menu);
            showGlobalContextActionBar();
        }
        super.onCreateOptionsMenu(menu, inflater);
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        return mDrawerToggle.onOptionsItemSelected(item) || super.onOptionsItemSelected(item);

    }

    /**
     * Per the navigation drawer design guidelines, updates the action bar to show the global app
     * 'context', rather than just what's in the current screen.
     */

    private void showGlobalContextActionBar() {
        ActionBar actionBar = getActionBar();
        actionBar.setDisplayShowTitleEnabled(true);
        //noinspection deprecation
        actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_STANDARD);
        actionBar.setTitle(R.string.app_name);
    }

    private ActionBar getActionBar() {
        return getActivity().getActionBar();
    }

    /**
     * Callbacks interface that all activities using this fragment must implement.
     */

    public interface NavigationDrawerCallbacks {
        /**
         * Called when an item in the navigation drawer is selected.
         */

        void onNavigationDrawerItemSelected(int position);
    }
}

Offline tonno16

  • Utente storico
  • *****
  • Post: 1228
  • Respect: +59
    • Mostra profilo
  • Dispositivo Android:
    moto g
  • Play Store ID:
    Diego Tonini
  • Sistema operativo:
    OpenSuse
Re:Cambiare lingua app sul MainDrawerFragment
« Risposta #1 il: 22 Ottobre 2015, 09:23:21 CEST »
0
Chiami getActivity().getResource()