简体   繁体   中英

get Item return pagerAdapter

I have viewPager with three fragments in it. When I return them in getItem(), I get an error. I've tried lots of different ways.Can you help me, please?

public Fragment getItem(int pos) {

        switch(pos){
        case 0: return FirstCreationPageOne.create(pos);
        case 1: return FirstCreationPageTwo.create(pos);
        case 2: return FirstCreationPageThree.create(pos);
        }
        /*switch (pos) {
        case 0:
            return new FirstCreationPageOne();
        case 1:
            return new FirstCreationPageTwo();
        case 2:
            return new FirstCreationPageThree();
        }*/
    }

Below is the code for create method. It is similar to all.

 public static FirstCreationPageThree create(int pageNumber) {
        FirstCreationPageThree fragment = new FirstCreationPageThree();
        Bundle args = new Bundle();
        args.putInt(ARG_PAGE, pageNumber);
        fragment.setArguments(args);
        return fragment;
    }

Eclipse gives an error: "This method must return a result of type Fragment". And offers me to add return statement of to change method type to void.

import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;

Thank you for your help! And sorry for my English.

The problem is your switch statement. If pos is greater than 2 it won't match any of your cases and so won't hit any return statement. This mightn't be possible in your app, but the compiler doesn't know that!

You can fix it by adding a default case to the switch

switch(pos){
    case 0: return FirstCreationPageOne.create(pos);
    case 1: return FirstCreationPageTwo.create(pos);
    case 2: return FirstCreationPageThree.create(pos);
    default: return DefaultFragment; //FirstCreationPageOne.create(pos) or some such
}

确保您的getCount方法返回3

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM