调用函数/方法时出错?

时间:2017-05-30 03:09:25

标签: java android android-fragments android-viewpager android-tablayout

由于某种原因,当我调用addFrag函数/方法来填充我的片段和字符串标题时,我收到错误。我正在使用适配器创建一个简单的ViewPager。顺便说一下,这一切都在片段中。这是代码:

public class HomeFragment extends Fragment {

    private View view;
    private ViewPager viewPager;
    private TabLayout tabLayout;
    private PagerAdapter adapter;

    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup viewGroup,
                             @Nullable Bundle savedInstanceState) {
        view = inflater.inflate(R.layout.home_fragment, viewGroup, false);

        viewPager = (ViewPager) view.findViewById(R.id.viewpager);
        setUpViewPager(viewPager);

        tabLayout = (TabLayout) view.findViewById(R.id.sliding_tabs);
        tabLayout.post(new Runnable() {
            @Override
            public void run() {
                tabLayout.setupWithViewPager(viewPager);
            }
        });
        return view;
    }



    private void setUpViewPager(ViewPager viewPager) {
        adapter = new ViewPagerAdapter(getChildFragmentManager());
        adapter.addFrag(new ContentFragment(), "ONE");
        adapter.addFrag(new ContentFragment(), "TWO");
        adapter.addFrag(new ContentFragment(), "THREE");
        viewPager.setAdapter(adapter);
    }


}

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

    //Default Fragment Constructor
    public ViewPagerAdapter(FragmentManager fm) {
        super(fm);
    }


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

    @Override
    public int getCount() {
        return fragmentList.size();
    }
    public void addFrag(Fragment fragment, String title){
        fragmentList.add(fragment);
        tabTitles.add(title);
    }
    @Override
    public CharSequence getPageTitle(int position){
        return tabTitles.get(position);
    }

}

当我尝试键入adapter.addFrag(new ExampleFragment(), "Hello");时,我收到错误无法解析方法addFrag。任何帮助将不胜感激。

2 个答案:

答案 0 :(得分:2)

adapter被声明为PagerAdapter,而不是ViewPagerAdapter。因此,adapter上可以使用的唯一方法是为PagerAdapter定义的方法。编译器不知道那时adapter实际上是ViewPagerAdapter - 我可以告诉它,因为我在上面看到了赋值adapter = new ViewPagerAdapter(...),但编译器不是不允许注意到(那些是语言的规则)。代替:

ViewPagerAdapter viewPagerAdapter = new ViewPagerAdapter(getChildFragmentManager());

使用viewPagerAdapter来调用addFrag方法,最终分配adapter = viewPagerAdapter;

答案 1 :(得分:1)

private PagerAdapter adapter;更改为private ViewPagerAdapter adapter;

将强制转换适配器输入ViewPagerAdapter,然后调用addFlag

((ViewPagerAdapter)adapter).addFlag(new ContentFragment(), "ONE");