我是Fragments的新手。我正在尝试开发滑动选项卡。从Activity调用Fragment方法,findFragmentById返回null
我有以下适配器:
public class HomeTabsPagerAdapter extends FragmentPagerAdapter {
public HomeTabsPagerAdapter(android.support.v4.app.FragmentManager fm) {
super(fm);
}
@Override
public android.support.v4.app.Fragment getItem(int idx) {
switch (idx) {
case CONSTS_MAIN.TAB_WATCH:
return new WatchFragment();
case CONSTS_MAIN.TAB_DISCOVER:
return new DiscoverFragment();
case CONSTS_MAIN.TAB_LOG:
return new LogFragment();
}
return null;
}
@Override
public int getCount() {
return CONSTS_MAIN.HOME_NO_OF_TABS;
}
}
和MainActivity.java
public class MainActivity extends FragmentActivity implements ActionBar.TabListener {
}
,当然,分片类:
public class WatchFragment extends Fragment {
public class DiscoverFragment extends Fragment {
public class LogFragment extends Fragment {
,基本上一切似乎做工精细图形。
但是,我试图从活动中调用碎片的方法。我这样做:
FragmentManager fm = getSupportFragmentManager();
WatchFragment watchFragment = (WatchFragment) fm.findFragmentById(R.id.watch_fragment);
watchFragment.refresh();
和这里fm.findFragmentById
总是返回null。
我一直在使用android.support.v4.app
。
如何获得片段类?
编辑:
这里是片段的布局:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id ="@+id/watch_fragment"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:label="@string/title_activity_watch"
android:orientation="vertical" >
<com.x.y.custom_controls.CustomWatchChronologicalListView
android:id="@+id/lvWatchChronologicalDiscussions"
android:layout_width="match_parent"
android:layout_height="match_parent" />
</RelativeLayout>
,这里是活动的布局
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent">
<android.support.v4.view.ViewPager
android:id="@+id/pager"
android:layout_width="match_parent"
android:layout_height="match_parent" >
</android.support.v4.view.ViewPager>
</RelativeLayout>
也许你正在使用'WatchFragment watchFragment =(WatchFragment)fm.findFragmentById(R.id.watch_fragment)ID;'不正确。你确定'WatchFragment'被加载到'R.id.watch_fragment'?请检查。 – Rohit5k2
你如何处理碎片?你是动态还是静态地将它们添加到XML布局中? –
我添加了片段和活动的布局。 @Rohit请看看Id是否不正确。 – dsb