类强制转换异常:片段1无法强制转换为片段2

时间:2017-09-18 00:55:38

标签: java android android-fragments casting

我现在有一个项目需要使用2个片段。在我的mainActivity内部,我从两个片段调用两个方法来初始化它们的适配器。我现在面临的问题是,当我将方法调用到第二个片段时,我得到一个类转换异常,说我的片段1不能转换为片段2。

我导入了正确的库import android.support.v4.app.Fragment,所以我不知道为什么会收到错误。

这是我定义片段的Activity的一部分:

@Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        //toolbar = (Toolbar) findViewById(R.id.toolbar);
        //setSupportActionBar(toolbar);

        token = SharedPrefsHelper.getString(getApplicationContext(), Constants.TOKEN);

        getSupportActionBar().setDisplayHomeAsUpEnabled(true);

        viewPager = (ViewPager) findViewById(R.id.viewpager);
        setupViewPager(viewPager);

        tabLayout = (TabLayout) findViewById(R.id.tabs);
        tabLayout.setupWithViewPager(viewPager);

        SendNetworkRequest(0);
        SendNetworkRequest(1);
    }

    private void setupViewPager(ViewPager viewPager) {
        ViewPagerAdapter adapter = new ViewPagerAdapter(getSupportFragmentManager());
        adapter.addFragment(new InternsFragment(), "Internos");
        adapter.addFragment(new ExternsFragment(), "Externos");
        viewPager.setAdapter(adapter);
    }

    class ViewPagerAdapter extends FragmentPagerAdapter {
        private final List<Fragment> mFragmentList = new ArrayList<>();
        private final List<String> mFragmentTitleList = new ArrayList<>();

        public ViewPagerAdapter(FragmentManager manager) {
            super(manager);
        }

        @Override
        public Fragment getItem(int position) {
            return mFragmentList.get(position);
        }

        @Override
        public int getCount() {
            return mFragmentList.size();
        }

        public void addFragment(Fragment fragment, String title) {
            mFragmentList.add(fragment);
            mFragmentTitleList.add(title);
        }

        @Override
        public CharSequence getPageTitle(int position) {
            return mFragmentTitleList.get(position);
        }
    }

这是我在Activity中的第一个片段调用方法的时候:

if (listUsers != null && !listUsers.isEmpty()) {
                            ExternsFragment fragment = (ExternsFragment) getSupportFragmentManager().findFragmentById(R.id.viewpager);
                            fragment.initAdapter(listUsers);
                        }

这是我从我的Activity中的第二个片段调用方法的时候:

if (!response.body().isEmpty()) {
                        listTeams = response.body();

                        InternsFragment fragment = (InternsFragment) getSupportFragmentManager().findFragmentById(R.id.viewpager);
                        fragment.initAdapter();

                        for ( int j = 0; j < listTeams.size(); j ++) {
                            System.out.println(listTeams.get(j).getName());
                        }
                    }

这是第一个片段的代码:

public class ExternsFragment extends Fragment {

    //@BindView(R.id.recycler_view) RecyclerView recyclerView;
    private TeamAdapter teamAdapter;
    private RecyclerView recyclerView;

    public ExternsFragment() {
        // Required empty public constructor
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        View rootView = inflater.inflate(R.layout.fragment_externs, container, false);
        recyclerView = (RecyclerView) rootView.findViewById(R.id.recycler_view);
        recyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));

        return rootView;
    }

    public void initAdapter(List<UserProject> userList) {

        teamAdapter = new TeamAdapter(getActivity(), userList);

        recyclerView.setAdapter(teamAdapter);

    }
}

这是第二个:

public class InternsFragment extends Fragment{

    private RecyclerView recyclerView;
    List<ListItem> consolidatedList = new ArrayList<>();
    private GroupAdapter adapter;

    public InternsFragment() {
        // Required empty public constructor
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        View rootView = inflater.inflate(R.layout.fragment_interns, container, false);
        recyclerView = (RecyclerView) rootView.findViewById(R.id.recycler_view);
        recyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));

        return rootView;
    }

    private HashMap<String, List<UserProject>> groupDataIntoHashMap(List<UserProject> listOfPojosOfJsonArray) {

        HashMap<String, List<UserProject>> groupedHashMap = new HashMap<>();

        for (UserProject pojoOfJsonArray : listOfPojosOfJsonArray) {

            String hashMapKey = pojoOfJsonArray.getTeamId();

            if (groupedHashMap.containsKey(hashMapKey)) {
                // The key is already in the HashMap; add the pojo object
                // against the existing key.
                groupedHashMap.get(hashMapKey).add(pojoOfJsonArray);
            } else {
                // The key is not there in the HashMap; create a new key-value pair
                List<UserProject> list = new ArrayList<>();
                list.add(pojoOfJsonArray);
                groupedHashMap.put(hashMapKey, list);
            }
        }


        return groupedHashMap;
    }

    public void initAdapter() {
        HashMap<String, List<UserProject>> groupedHashMap = groupDataIntoHashMap(ActivityTeams.listUsers);


        for (String date : groupedHashMap.keySet()) {
            TeamItem dateItem = new TeamItem();
            dateItem.setTeam(date);
            consolidatedList.add(dateItem);


            for (UserProject pojoOfJsonArray : groupedHashMap.get(date)) {
                GeneralItem generalItem = new GeneralItem();
                generalItem.setPojoOfJsonArray(pojoOfJsonArray);//setBookingDataTabs(bookingDataTabs);
                consolidatedList.add(generalItem);
            }
        }


        adapter = new GroupAdapter(getActivity(), consolidatedList);
        LinearLayoutManager layoutManager = new LinearLayoutManager(getActivity());
        layoutManager.setOrientation(LinearLayoutManager.VERTICAL);
        recyclerView.setLayoutManager(layoutManager);
        recyclerView.setAdapter(adapter);
    }

}

1 个答案:

答案 0 :(得分:0)

将您的片段作为活动的类变量。

InternsFragment mInternsFragment;
ExternsFragment mExternsFragment; 

//inside oncreate
mInternsFragment = new InternsFragment ();
mExternsFragment = new ExternsFragment ();

adapter.addFragment( mInternsFragment, "Internos" );     
adapter.addFragment( mExternsFragment, "Externos" );

然后直接在活动内的任何地方使用它们。