Android TabPagerAdapter:在较旧的 API 上无法正常工作

Android TabPagerAdapter: not working properly on older APIs

我遇到了 FragmentPagerAdapter 的问题。

我已经在我的应用程序的其他部分成功地使用了它,但现在我 运行 遇到了这个讨厌的问题:在旧的 API 上,当我从一个选项卡滑动到另一个选项卡时,一切都是工作完美,但是当我通过单击标题更改选项卡时,它被选中,但底层片段没有改变。

我开始认为问题可能是由于此寻呼机嵌套在另一个片段中引起的。不过,奇怪的是,我可以通过滑动来更改选项卡,但不能通过单击标题来更改。

这是我的代码:

public class PetrolStationFragment extends Fragment {

private PetrolStation mPetrolStation;

private int mPetrolStationIndex;

private AppCompatImageView mLogo;
private TextView mNameTextView;
private CheckBox mCheckBox;
private TextView mAddressTextView;
private TextView mDistanceTextView;
private Switch mSwitch;
private GoogleMap mGoogleMap;

private static TabLayout mTabLayout;
private static ViewPager mViewPager;
private static int intItems = 2;


// Design pattern to instantiate a new fragment.
public static PetrolStationFragment newInstance(int petrolStationIndex) {
    Bundle args = new Bundle();
    args.putInt(ARG_PETROL_STATION_INDEX, petrolStationIndex);

    PetrolStationFragment fragment = new PetrolStationFragment();
    fragment.setArguments(args);

    return fragment;
}

/********************************************************/

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

    mPetrolStationIndex = getArguments().getInt(ARG_PETROL_STATION_INDEX);
    mPetrolStation = PetrolStationsArray.get().getItem(mPetrolStationIndex);
}

@Override
public void onPause() {
    super.onPause();
}

@Override
public void onResume() {
    super.onResume();
}

public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceStace) {
    View view = inflater.inflate(R.layout.fragment_petrol_station, container, false);

    mLogo = (AppCompatImageView) view.findViewById(R.id.ps_logo);
    mNameTextView = (TextView) view.findViewById(R.id.petrol_station);
    mCheckBox = (CheckBox) view.findViewById(R.id.checkbox);
    mAddressTextView = (TextView) view.findViewById(R.id.address);
    mDistanceTextView = (TextView) view.findViewById(R.id.distance);
    mSwitch = (Switch) view.findViewById(R.id.on_service);

    mLogo.setImageDrawable(ContextCompat.getDrawable(getActivity(), getPetrolStationLogo(mPetrolStation.getLogo())));
    mNameTextView.setText(mPetrolStation.getName());
    mCheckBox.setChecked(mPetrolStation.isFavourite());
    mAddressTextView.setText(mPetrolStation.getAddress());

    // To start the marquee-effect on the address TextView.
    mAddressTextView.setSelected(true);

    LatLng centre = getLocation();
    LatLng point = new LatLng(mPetrolStation.getLat(), mPetrolStation.getLon());

    if (centre == null) {
        mDistanceTextView.setText(getResources().getString(R.string.distence_nd));
    } else {
        double distance = computeDistance(centre, point);
        mDistanceTextView.setText(getResources().getString(R.string.distance_km, distance));
    }

    // TODO: to fix.
    mCheckBox.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
        @Override
        public void onCheckedChanged(CompoundButton compoundButton, boolean isFavourite) {
            // mPetrolStation.setFavourite(isFavourite);
        }
    });

    ((SupportMapFragment) getChildFragmentManager().findFragmentById(R.id.map)).getMapAsync(new OnMapReadyCallback() {
        @Override
        public void onMapReady(GoogleMap googleMap) {
            mGoogleMap = googleMap;
            mGoogleMap.getUiSettings().setAllGesturesEnabled(false);

            double lat = mPetrolStation.getLat();
            double lon = mPetrolStation.getLon();
            LatLng latLng = new LatLng(lat, lon);

            mGoogleMap.addMarker(new MarkerOptions().position(latLng));

            CameraUpdate cameraUpdate = CameraUpdateFactory.newLatLngZoom(latLng, 15);
            mGoogleMap.moveCamera(cameraUpdate);
        }
    });

    // Setup Views.
    mTabLayout = (TabLayout) view.findViewById(R.id.pager_header);
    mViewPager = (ViewPager) view.findViewById(R.id.pager);

    // Set an Adapter for the View Pager.
    TabPagerAdapter tabPagerAdapter = new TabPagerAdapter(getChildFragmentManager());
    mViewPager.setAdapter(tabPagerAdapter);
    mTabLayout.setupWithViewPager(mViewPager);

    mViewPager.setCurrentItem(SELF_SERVICE_TAB_POSITION);

    mTabLayout.setOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
        @Override
        public void onTabSelected(TabLayout.Tab tab) {
            mViewPager.setCurrentItem(tab.getPosition());
        }

        @Override
        public void onTabUnselected(TabLayout.Tab tab) {

        }

        @Override
        public void onTabReselected(TabLayout.Tab tab) {

        }
    });

    return view;
}

@Override
public void onViewCreated(View view, Bundle savedInstanceState) {
    super.onViewCreated(view, savedInstanceState);
}

class TabPagerAdapter extends FragmentPagerAdapter {

    public TabPagerAdapter(FragmentManager fm) {
        super(fm);
    }

    // Return fragment with respect to position.
    @Override
    public Fragment getItem(int position) {
        Fragment fragment;

        switch (position) {

            case SELF_SERVICE_TAB_POSITION: {
                fragment = SelfServiceFragment.newInstance(mPetrolStationIndex);

                return fragment;
            }

            case FULL_SERVICE_TAB_POSITION: {
                fragment = FullServiceFragment.newInstance(mPetrolStationIndex);

                return fragment;
            }

        }

        return null;
    }

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

    // This method returns the title of the tab according to its position.
    @Override
    public CharSequence getPageTitle(int position) {
        switch (position) {

            case SELF_SERVICE_TAB_POSITION: {
                String mSelfService = getResources().getString(R.string.self_service);

                return mSelfService;
            }

            case FULL_SERVICE_TAB_POSITION: {
                String mFullService = getResources().getString(R.string.full_service);

                return mFullService;
            }

        }

        return null;
    }

}

}

我猜你在一个片段中创建了新的片段。我在类似的场景中使用了片段,我在 tabadapter.the 代码中创建了新的片段实例,代码如下所示:

public class TabsPagerAdapter 扩展了 FragmentPagerAdapter {

public TabsPagerAdapter(FragmentManager fm) {
    super(fm);
}

@Override
public Fragment getItem(int position) {
    switch (position){
        case 0:
            return new MeFragment();
        case 1:
            return new CommunityFragment();
    }
    return null;
}

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

}

我正在添加这个主要活动看看它,也许它会有所帮助:

public class MainActivity extends AppCompatActivity {

private Toolbar toolbar;
private TabLayout tabLayout;
private ViewPager viewPager;
public static Activity activity;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    activity = this;
    toolbar = (Toolbar) findViewById(R.id.toolbar);
    setSupportActionBar(toolbar);

    getSupportActionBar().setDisplayHomeAsUpEnabled(false);

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

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

}

private void setupViewPager(ViewPager viewPager){
    ViewPagerAdapter adapter = new ViewPagerAdapter(getSupportFragmentManager());
    adapter.addFragment(new MeFragment(),"Me");
    adapter.addFragment(new CommunityFragment(),"Community");
    viewPager.setAdapter(adapter);
}

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

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

    @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);
    }
}

}

解决方案很明显:我使用的是 static TabLayout 和一个 static ViewPager:这是一个错误,因为我的 TabPager 在另一个 ViewPager 中。