我有一个tablayout使用片段和viewpager。现在在我的第二个标签中,我有这个布局。 在两个片段之间传递数据与列表视图
在左边,我有一个加载的片段,ListPlacesFragment。在右边是一个不同的片段,DetailsPlacesFrament。当我点击列表视图上的一个项目时,我想将其显示在正确的片段上。我已经使用意图的活动,但我不知道如何将列表的索引传递给右侧的片段以显示适当的细节。请帮忙谢谢!
我有一个tablayout使用片段和viewpager。现在在我的第二个标签中,我有这个布局。 在两个片段之间传递数据与列表视图
在左边,我有一个加载的片段,ListPlacesFragment。在右边是一个不同的片段,DetailsPlacesFrament。当我点击列表视图上的一个项目时,我想将其显示在正确的片段上。我已经使用意图的活动,但我不知道如何将列表的索引传递给右侧的片段以显示适当的细节。请帮忙谢谢!
您应该使用您的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);
然后,您可以创建您使用该索引中的详细信息发送到正确的片段的公共方法。
让我们说,这是你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
,这可以通过使用列表项
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);
}
}
的
position
定义它对不起兄弟,你能给我一个想法如何实现接口? – Jeongbebs我编辑了更多的细节。这有帮助吗? –
等我试试吧 – Jeongbebs