Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
250 views
in Technique[技术] by (71.8m points)

android - Passing data between two fragments with listview

I have a tablayout using fragments and viewpager. Now in my second tab, I have this layout. enter image description here

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!

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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);
    }
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...