以下是我的设置:我有MainActivity
,其中包含以下代码:
public class MainActivity extends FragmentActivity {
FragmentList listFragment;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.layout);
listFragment = new FragmentList();
FragmentManager fragmentManager = getSupportFragmentManager();
FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
fragmentTransaction.add(R.id.list_container, listFragment);
fragmentTransaction.commit();
}
}
然后我有FragmentList
,这是ListView
片段和FragmentDetail
,这是选择特定ListView
行时显示的片段。
这是FragmentList
代码的片段:
public class FragmentList extends Fragment {
private ListView list;
private FragmentDetail detailFragment;
private long detailId;
private ViewPager mPager;
private PagerAdapter mPagerAdapter;
@Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
// ListView gets set via an adapter
list.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
detailId = id;
mPager = (ViewPager)getActivity().findViewById(R.id.pager);
mPagerAdapter = new ScreenSlidePagerAdapter(getFragmentManager());
mPager.setAdapter(mPagerAdapter);
final FragmentManager fragmentManager = getActivity().getSupportFragmentManager();
final FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
fragmentTransaction.replace(R.id.list_container, detailFragment);
fragmentTransaction.commit();
}
});
}
private class ScreenSlidePagerAdapter extends FragmentStatePagerAdapter {
public ScreenSlidePagerAdapter(FragmentManager fm) {
super(fm);
}
@Override
public Fragment getItem(int position) {
detailFragment = new FragmentDetail();
Bundle mBundle = new Bundle();
mBundle.putLong("detailId", detailId);
detailFragment.setArguments(mBundle);
return detailFragment;
}
@Override
public int getCount() {
return 5;
}
}
}
FragmentDetail
:
public class FragmentDetail extends Fragment {
private long id;
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
ViewGroup rootView = (ViewGroup) inflater.inflate(R.layout.activity_view, container, false);
return rootView;
}
@Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
Bundle bundle = getArguments();
id = bundle.getLong("detailId");
// Set views based on id
}
}
以下是我的问题:
fragmentTransaction.replace(R.id.list_container, detailFragment);
中的行FragmentList
错误地说我无法更改容器的ID。那是为什么?谢谢!