无法在v4中将v4.FragmentActivity强制转换为v4.Fragment?

时间:2016-03-10 21:40:49

标签: java android android-fragments android-fragmentactivity

我对android.support.v4.appFragmentFragmentTabHost使用Fragment。我的目标是在片段内部显示两个选项卡。所以我遵循了以下过程:

ListingFragment

public class ListingFragment extends Fragment {
private FragmentTabHost mTabHost;

public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {
  View rootView = inflater.inflate(R.layout.fragment_listing_home,container, false);
  mTabHost = (FragmentTabHost)rootView.findViewById(R.id.tabHost);

  mTabHost.setup(getActivity(), getChildFragmentManager(), R.id.realtabcontent);
  mTabHost.addTab(mTabHost.newTabSpec("listfragment").setIndicator("Fragment List"), ListingFragmentTabHost.class, null);
  return rootView;
}

ListingFrgmentTabHost

public class ListingFragmentTabHost extends FragmentActivity {
   ....
   ....
}

FragmentActivityimport android.support.v4.app.FragmentActivity;

fragment_listing_home

<android.support.v4.app.FragmentTabHost
 xmlns:android="http://schemas.android.com/apk/res/android"
 android:id="@+id/tabHost"
 android:layout_width="match_parent"
 android:layout_height="match_parent">

<LinearLayout
    android:orientation="vertical"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <FrameLayout
        android:id="@+id/realtabcontent"
        android:layout_width="match_parent"
        android:layout_height="0dp"
        android:layout_weight="1"/>

</LinearLayout>
</android.support.v4.app.FragmentTabHost>

但是当我运行上面的代码片段时。它给我cast例外java.lang.ClassCastException: com.app.grabhouse.fragment.ListingFragmentTabHost cannot be cast to android.support.v4.app.Fragment

为什么会这样?

修改

在我提出建议后,我已将FragmentActivity转换为Fragment

public class ListingFragmentTabHost extends Fragment {

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {
    View rootView = inflater.inflate(R.layout.fragment_listing_home, container, false);
    return rootView;
}

@Override
public void onActivityCreated(@Nullable Bundle savedInstanceState) {
    recyclerView = (RecyclerView) getView().findViewById(R.id.mRecyclerView);
    super.onActivityCreated(savedInstanceState);
    LinearLayoutManager llm = new LinearLayoutManager(getActivity());
    llm.setOrientation(LinearLayoutManager.VERTICAL);
    recyclerView.setLayoutManager(llm);

    HomeRecyclerViewAdapter homeRecyclerViewAdapter = new HomeRecyclerViewAdapter(getActivity().getApplicationContext());
    recyclerView.setAdapter(homeRecyclerViewAdapter);
}
}

1 个答案:

答案 0 :(得分:0)

因为您需要将片段传递到addTab并且ListingFragmentTabHost不是片段,所以它是一项活动