使用listview在两个片段之间传递数据

时间:2013-10-29 02:54:47

标签: android android-fragments

我有一个使用片段和viewpager的tablayout。现在在我的第二个标签中,我有这个布局。 enter image description here

在左边,我加载了一个片段ListPlacesFragment。右边是一个不同的Fragment,DetailsPlacesFrament。当我单击列表视图上的项目时,我想在右侧片段上显示它。我在活动上使用了意图,但我不知道如何将列表的索引传递给右边的片段以显示相应的细节。请帮助谢谢!

2 个答案:

答案 0 :(得分:1)

假设这是包含Activity

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

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

的内容
AdapterView.OnItemClickListener listener = new AdapterView.OnItemClickListener() {
    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
        displayDetailsPlacesFragment(position);
    }
}

以及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来定义它

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

答案 1 :(得分:0)

您应该将Activity用作两个片段之间的中介。我要做的是创建一个活动将实现的接口,如PlaceClickListener:

public interface PlaceClickListener{
    public void onPlaceClicked(int index);
}

在您的活动中,您必须实施它:

class MainActivity implements PlaceClickListener {

    /* other code */

    public void onPlaceClicked(int index){
        /* call function for detail fragment here */
    }
}

然后在列表片段中点击某个项目时执行以下操作:

((PlaceClickListener)getActivity()).onPlaceClicked(int index);

然后,您可以在右侧片段中创建一个公共方法,使用索引将详细信息发送到。

相关问题