使用listview在两个片段之间传递数据 [英] Passing data between two fragments with listview

查看:34
本文介绍了使用listview在两个片段之间传递数据的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个使用片段和viewpager的TabLayout.现在在我的第二个选项卡中,我有了这个布局.

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

在左侧,我加载了一个片段,即ListPlacesFragment.右边是另一个片段,DetailsPlacesFrament.当我单击列表视图上的项目时,我想在正确的片段上显示它.我已经在活动中使用了意图,但是我不知道如何将列表的索引传递给右侧的片段以显示适当的详细信息.请帮忙谢谢!

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!

推荐答案

假设这是您的 Activity ,其中包含 DetailsPlacesFragment

Let's say that this is your Activity that contains DetailsPlacesFragment

================================================================
|                   |                                          |
|    ListView       |        FrameLayout                       |
|                   |                                          |
================================================================

在您的 ListView 中,将适配器设置为类似

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

,以及 Activity 中的可替换片段,

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

,对于您的 DetailsPlacesFragment ,您可以通过传递列表项的 position 进行定义

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

这篇关于使用listview在两个片段之间传递数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆