Autore Topic: Cambiare contenuto di un fragment da una ExpandableListView  (Letto 456 volte)

Offline ValerioAdo

  • Utente normale
  • ***
  • Post: 323
  • Respect: 0
    • Mostra profilo
  • Dispositivo Android:
    Huawei Ascend g525
  • Sistema operativo:
    windows 8.1
Cambiare contenuto di un fragment da una ExpandableListView
« il: 31 Agosto 2015, 12:25:29 CEST »
0
Salve a tutti!

La mia app ha uno sliding menu contenente una ExpandableListView (precedentemente era un ListView normale ma ho visto che non era proprio comodissima come navigazione per i miei scopi, pertanto ho effettuato il morphing) con 5 gruppi di cui solo 2 hanno un sotto menu.
Riesco a gestire benissimo la navigazione all'interno del menu (cioè riconoscere quando clicca un sottomenu o quando clicca un gruppo).
Nella mi pagina pricipale ho un fragment che mi visualizza una lista (Home) e qui viene il problema:
Quando selezione un sottomenu sono tranquillo perché faccio partire un intent che mi visualizza una pagina dedicata, mentre quando seleziono Home,Premi,FAQ'S mi dovrebbe cambiare il contenuto del fragment e non so come gestirlo col questo tipo di menu.

Questo è il codice che uso per la gestione dello slidemenu e dell'ExpandableListView:
Codice (Java): [Seleziona]
/**
 * 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 {

    /**
     * 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.
     */

    private ActionBarDrawerToggle mDrawerToggle;

    private DrawerLayout mDrawerLayout;
    private View mFragmentContainerView;

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

    private ExpandableListView mDrawerListView;
    ExpandableListAdapter listAdapter;
    List<String> listDataHeader;
    HashMap<String, List<String>> listDataChild;


    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(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        mDrawerListView = (ExpandableListView) inflater.inflate(
                R.layout.fragment_navigation_drawer, container, false);

        // Listview on child click listener

        mDrawerListView.setOnGroupClickListener(new ExpandableListView.OnGroupClickListener() {
            @Override
            public boolean onGroupClick(ExpandableListView parent, View v, int groupPosition, long id) {
                switch (groupPosition){
                    case 0:
                        return true;
                    case 3:
                        return true;
                    case 4:
                        return true;
                }
                return false;
            }
        });


        mDrawerListView.setOnChildClickListener(new ExpandableListView.OnChildClickListener() {

            @Override
            public boolean onChildClick(ExpandableListView parent, View v,
                                        int groupPosition, int childPosition, long id) {
                Toast.makeText(
                        getActivity(),
                        listDataHeader.get(groupPosition)
                                + " : "
                                + listDataChild.get(
                                listDataHeader.get(groupPosition)).get(
                                childPosition), Toast.LENGTH_SHORT)
                        .show();

                switch(groupPosition){
                    case 1:
                        switch (childPosition){
                            case 0:
                                Intent points = new Intent(getActivity(), Punti.class);
                                startActivity(points);
                                break;

                            case 1:
                                Intent storico = new Intent(getActivity(), Storico.class);
                                startActivity(storico);
                                break;

                            case 2:
                                Intent statistiche = new Intent(getActivity(), Statistiche.class);
                                startActivity(statistiche);
                                break;
                        }
                        break;
                    case 2:
                        switch (childPosition){
                            case 0:
                                Intent risp = new Intent(getActivity(), Risparmiatore.class);
                                startActivity(risp);
                                break;

                            case 1:
                                Intent buyer = new Intent(getActivity(), Buyer.class);
                                startActivity(buyer);
                        }
                        break;
                }
                return false;
            }
        });

        listDataHeader = new ArrayList<String>();
        listDataChild = new HashMap<String, List<String>>();

        // Adding child data
        listDataHeader.add(getString(R.string.title_section5));
        listDataHeader.add(getString(R.string.title_section1));
        listDataHeader.add(getString(R.string.title_section2));
        listDataHeader.add(getString(R.string.title_section3));
        listDataHeader.add(getString(R.string.title_section4));

        // Adding child data
        List<String> MyProfile = new ArrayList<String>();
        MyProfile.add("Punti");
        MyProfile.add("Storico Acquisti");
        MyProfile.add("Statistiche");

        List<String> Classifiche = new ArrayList<String>();
        Classifiche.add("Top Risparmiatore");
        Classifiche.add("Top Buyer");


        listDataChild.put(listDataHeader.get(1), MyProfile); // Header, Child data
        listDataChild.put(listDataHeader.get(2), Classifiche);

        /*mDrawerListView.setAdapter(new ArrayAdapter<String>(
                getActionBar().getThemedContext(),
                android.R.layout.simple_list_item_activated_1,
                android.R.id.text1,
                new String[]{
                        getString(R.string.title_section5),
                        getString(R.string.title_section1),
                        getString(R.string.title_section2),
                        getString(R.string.title_section3),
                        getString(R.string.title_section4),
                }));*/


        listAdapter = new ExpandableListAdapter(getActivity(), listDataHeader, listDataChild);

        mDrawerListView.setAdapter(listAdapter);

        mDrawerListView.setItemChecked(mCurrentSelectedPosition, true);
        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(R.drawable.drawer_shadow, GravityCompat.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.
        mDrawerToggle = new ActionBarDrawerToggle(
                getActivity(),                    /* host Activity */
                mDrawerLayout,                    /* DrawerLayout object */
                R.drawable.ic_drawer,             /* 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().supportInvalidateOptionsMenu(); // 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().supportInvalidateOptionsMenu(); // 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.global, menu);
            showGlobalContextActionBar();
        }
        super.onCreateOptionsMenu(menu, inflater);
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        if (mDrawerToggle.onOptionsItemSelected(item)) {
            return true;
        }

        if (item.getItemId() == R.id.action_example) {
            Toast.makeText(getActivity(), "Example action.", Toast.LENGTH_SHORT).show();
            return true;
        }

        return 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);
        actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_STANDARD);
        actionBar.setTitle(R.string.app_name);
    }

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

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

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

        void onNavigationDrawerItemSelected(int position);
    }
}

mentre con questo pezzo di codice io cambiavo il contenuto del fragment quando ancora avevo un listView normale:
Codice (Java): [Seleziona]
  public void onSectionAttached(int number) {
        switch (number) {
            case 1:
                mTitle = getString(R.string.title_section5);
                //Intent profile = new Intent(MainActivity.this, MyProfile.class);
                //startActivity(profile);

                Home newFragmenthome = new Home();

                Bundle argshome = new Bundle();
                //args.putInt(newFragment.ARG_POSITION, position);
                newFragmenthome.setArguments(argshome);

                android.support.v4.app.FragmentTransaction transactionhome = getSupportFragmentManager().beginTransaction();

                // Replace whatever is in the fragment_container view with this fragment,
                // and add the transaction to the back stack so the user can navigate back
                transactionhome.replace(R.id.fragment2, newFragmenthome);
                transactionhome.addToBackStack(null);

                transactionhome.commit();
                break;
            case 2:
                mTitle = getString(R.string.title_section1);
                //Intent profile = new Intent(MainActivity.this, MyProfile.class);
                //startActivity(profile);

                MyProfileFragment newFragmentprofile = new MyProfileFragment();

                Bundle argsprofile = new Bundle();
                //args.putInt(newFragment.ARG_POSITION, position);
                newFragmentprofile.setArguments(argsprofile);

                android.support.v4.app.FragmentTransaction transactionprofile = getSupportFragmentManager().beginTransaction();

                // Replace whatever is in the fragment_container view with this fragment,
                // and add the transaction to the back stack so the user can navigate back
                transactionprofile.replace(R.id.fragment2, newFragmentprofile);
                transactionprofile.addToBackStack(null);

                // Commit the transaction
                transactionprofile.commit();

                break;
            case 3:
                mTitle = getString(R.string.title_section2);

                Classifiche newFragmentClassifiche = new Classifiche();

                Bundle argsClassifiche = new Bundle();
                //args.putInt(newFragment.ARG_POSITION, position);
                newFragmentClassifiche.setArguments(argsClassifiche);

                android.support.v4.app.FragmentTransaction transactionClassifiche = getSupportFragmentManager().beginTransaction();

                // Replace whatever is in the fragment_container view with this fragment,
                // and add the transaction to the back stack so the user can navigate back
                transactionClassifiche.replace(R.id.fragment2, newFragmentClassifiche);
                transactionClassifiche.addToBackStack(null);

                // Commit the transaction
                transactionClassifiche.commit();

                break;
            case 4:
                mTitle = getString(R.string.title_section3);

                FAQ newFragmentFAQ = new FAQ();

                Bundle argsFAQ = new Bundle();
                //args.putInt(newFragment.ARG_POSITION, position);
                newFragmentFAQ.setArguments(argsFAQ);

                android.support.v4.app.FragmentTransaction transactionPremi = getSupportFragmentManager().beginTransaction();

                // Replace whatever is in the fragment_container view with this fragment,
                // and add the transaction to the back stack so the user can navigate back
                transactionPremi.replace(R.id.fragment2, newFragmentFAQ);
                transactionPremi.addToBackStack(null);

                // Commit the transaction
                transactionPremi.commit();

                break;
            case 5:
                mTitle= getString(R.string.title_section4);
                break;
        }
    }

avete qualche suggerimento? grazie mille!

P.s.

Ho provato a scrivere il codice dell'ExpandableListView così:
Codice (Java): [Seleziona]
     mDrawerListView.setOnGroupClickListener(new ExpandableListView.OnGroupClickListener() {
            @Override
            public boolean onGroupClick(ExpandableListView parent, View v, int groupPosition, long id) {
                switch (groupPosition){
                    case 0:
                        MyProfileFragment newFragmentprofile = new MyProfileFragment();

                        Bundle argsprofile = new Bundle();
                        //args.putInt(newFragment.ARG_POSITION, position);
                        newFragmentprofile.setArguments(argsprofile);

                        android.support.v4.app.FragmentTransaction transactionprofile = getSupportFragmentManager().beginTransaction();

                        // Replace whatever is in the fragment_container view with this fragment,
                        // and add the transaction to the back stack so the user can navigate back
                        transactionprofile.replace(R.id.fragment2, newFragmentprofile);
                        transactionprofile.addToBackStack(null);

                        // Commit the transaction
                        transactionprofile.commit();
                        return true;
                    case 3:
                        return true;
                    case 4:
                        return true;
                }
                return false;
            }
        });

Ma ho un errore su "getSupportFragmentManager().beginTransaction();" del tipo "cannot resolve method:getSupportFragmentManager()" cosa posso metterci al posto di quello? (sempre se sono sulla via giusta).
« Ultima modifica: 31 Agosto 2015, 12:28:16 CEST da ValerioAdo »