w00
w00

Reputation: 26762

Switch from ListView to sub ListView in Android

I have an app where the MainActivity which creates an ActionBar with tabs (used ActionBarSherlock for this).

Each tab loads a Fragment. One fragment has a ListView in which I load items. Each item responds to an OnItemClick event.

When an item is clicked then the app gets data from a webserver. I want to show that data in a new ListView. But that's where i'm stuck.

How can I switch from my first main ListView to a 'sub-ListView`?

Keep in mind that my current View is a fragment and that it's loaded inside a tab. I want to remain on the same tab when I show the new 'sub' ListView.

Also, when I push the back button on the Android device, then I want it to show the main ListView again.

So actually, kinda like the iPhone does it with their TableView.

Upvotes: 1

Views: 616

Answers (1)

CinetiK
CinetiK

Reputation: 1758

You have te use another Fragment in order to do that. You need to create that Fragment and then replace the old one with the FragmentTransaction and if you want to use the "back" button you need to add the new fragment to the Backstack. If these ListFragment are quite different in terms of data, I'd have 2 fragment classes (e.g. : FirstListFragment, SecondListFragment).

Here's some code from an App I worked on :

    // Here I get the FragmentTransaction

    FragmentTransaction ft = getFragmentManager().beginTransaction();

    // I replace it with a new Fragment giving it data. Here you need to tell 
    // the FragmentTransaction what (or actually where) and by what you want to replace. 

    ft.replace(R.id.fraglist, new ModuleFragment(lpId, sqId, sqName));

The R.id.fraglist should be defined in your XML layout (except if you programmatically created your layout). It's simply the ID of your default fragment.

    // I set the animation

    ft.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_OPEN);

    // I add it to the backstack so I can use the back button

    ft.addToBackStack(null);

    // Then I finally commit so it happens !

    ft.commit();

You can also use a Bundle to parse data like so :

    Bundle moduleBundle = new Bundle();
    moduleBundle.putString("id", id);
    moduleBundle.putString("description", description);
    moduleFragment.setArguments(moduleBundle);

Upvotes: 1

Related Questions