简体   繁体   中英

How to switch to listview on drawer navigation menu item click

I want to open a listview when click on item for this i used listfragment and for drawer navigation i customized default drawer navigation activity when I'm clicking on menu item of navigation drawer, the whole listfragment opens instead of fragment inside drawer navigation and because of this Im unable to get back to drawer navigation activity(for clicking other items) as listfragment opens as separate fragment, here is my code

public boolean onNavigationItemSelected(MenuItem item) {
    // Handle navigation view item clicks here.
    int id = item.getItemId();

    if (id == R.id.teams) {
        Toast.makeText(this, "Teams clicked", Toast.LENGTH_SHORT).show();
        ListFragment listfrag
      =
(ListFragment)getSupportFragmentManager().findFragmentByTag("listfragment");

        if(listfrag==null){
           listfrag =new listFragment();

FragmentTransaction transact=getSupportFragmentManager().beginTransaction();
            transact.add(android.R.id.content,listfrag,"lstfragment");
            transact.commit();

        }

and code of listfragment

public class listFragment extends ListFragment {

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

   ViewGroup rootview = 
(ViewGroup) inflater.inflate(R.layout.customlistview, container, false);

    //data source
    String[] from = { "flag","txt","cur" };

 ArrayAdapter<String> adapter=new 
ArrayAdapter<String>(getActivity(),R.layout.listviewitem, R.id.tvteamsname, from);

    setListAdapter(adapter);
    //  Retain the ListFragment instance across Activity re-creation
    setRetainInstance(true);

    return rootview;

}

first add a frame to your Activity where you have added navigationDrawerMenu .

FragmentTransaction transact=getSupportFragmentManager().beginTransaction();
transact.add(android.R.id.content,listfrag,"lstfragment");
transact.commit();

replace this code with

FragmentTransaction transact=getSupportFragmentManager().beginTransaction();
transact.replace(R.id.your_frame, listfrag);
transact.addToBackStack(null); // or you can add some string
transact.commit();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM