Search code examples
javaandroidandroid-viewpager

Cannot access method by reference


When i access the method directly on the PagerAdapter creation i have the getViewAtPosition() method. When i try it using the reference, i can't. What may i do to get acecces by the reference?

Here i can: 1:enter image description here

Here i can't: 2: enter image description here

public class CardapioRU extends Fragment {

private ViewPager mPager;
private PagerAdapter mPagerAdapter;

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

    mPager = (ViewPager) rootView.findViewById(R.id.pager);
    mPagerAdapter = new PagerAdapterRU(inflater);
    mPager.setAdapter(mPagerAdapter);
    return rootView;
}

}

.

public class PagerAdapterRU extends PagerAdapter {

private View domingo = null;
private View segunda = null;

@SuppressLint("InflateParams")
public PagerAdapterRU(LayoutInflater inflater) {
    domingo = inflater.inflate(R.layout.ru_domingo, null);
    segunda = inflater.inflate(R.layout.ru_segunda, null);
}

public View getViewAtPosition(int position) {
    View view = null;
    if (position == 0) {
        view = domingo;
    }
    if (position == 1) {
        view = segunda;
    }
    ;
    return view;
};

@Override
public Object instantiateItem(View collection, int position) {
    View view = getViewAtPosition(position);
    ((ViewPager) collection).addView(view, 0);
    return view;
}

@Override
public int getCount() {
    return 2;
}

Solution

  • getViewAtPosition() is a method of PagerAdapterRU.

    On the first screenshot you're calling a method directly on your PagerAdapterRU instance, but on the second screenshot you're calling it on a PagerAdapter.

    It doesn't matter how you've initialized it, you've declared it as a PagerAdapter, so you have access to the methods of a PagerAdapter.

    To have access to the methods of the subclass, declare it with the type of the subclass.

    Change the following:

    private PagerAdapter mPagerAdapter;
    

    To this:

    private PagerAdapterRU mPagerAdapter;
    

    And you'll be able to call getViewAtPosition() on mPagerAdapter.