Reputation: 4120
I have a tablayout using fragments and viewpager. Now in my second tab, I have this layout.
In the left, I have a fragment loaded, ListPlacesFragment. On the right is a different Fragment, DetailsPlacesFrament. When I click an item on the listview, I want to display it on the right fragment. I have used intents on activity, but i don't know how to pass the index of the list to the fragment on the right to display the appropriate details. Please help thanks!
Upvotes: 0
Views: 1298
Reputation: 1789
Let's say that this is your Activity
that contains DetailsPlacesFragment
================================================================
| | |
| ListView | FrameLayout |
| | |
================================================================
In your ListView
, set the adapter to something like this
AdapterView.OnItemClickListener listener = new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
displayDetailsPlacesFragment(position);
}
}
and for the replaceable fragments in your Activity
,
public void displayDetailsPlacesFragment(int position) {
Fragment fragment = DetailsPlacesFragment.newInstance(position);
FragmentTransaction ft = getFragmentManager().beginTransaction();
ft.replace(R.id.content_frame, fragment); // FrameLayout id
ft.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_FADE);
ft.addToBackStack(null);
ft.commit();
}
and for your DetailsPlacesFragment
, you define it by passing the position
of the list item
public class DetailsPlacesFragment extends Fragment {
public static DetailsPlacesFragment newInstance(int position) {
DetailsPlacesFragment fragment = new DetailsPlacesFragment();
Bundle args = new Bundle();
args.putInt("position", position);
fragment.setArguments(args);
return fragment;
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle icicle) {
int position = getArguments().getInt("position"); // use this position for specific list item
return super.onCreateView(inflater, container, icicle);
}
}
Upvotes: 1
Reputation: 268
You should use your Activity as a mediator between the two fragments. What I would do is create an interface that the activity will implement like PlaceClickListener:
public interface PlaceClickListener{
public void onPlaceClicked(int index);
}
In your activity, you have to implement it:
class MainActivity implements PlaceClickListener {
/* other code */
public void onPlaceClicked(int index){
/* call function for detail fragment here */
}
}
Then in your list fragment do something such as this when you click on an item:
((PlaceClickListener)getActivity()).onPlaceClicked(int index);
Then you can create a public method in the right fragment that you use the index to send the details to.
Upvotes: 0