Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
263 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 Reply

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...