我有一個可滑動片段的viewpager,還有一個顯示選擇哪個視圖的radiogroup。當我啓動應用程序時,第一個單選按鈕未被選中,只有當我滑動另一個視圖並返回時纔會被選中。我是初學者,所以請分享你的知識。這裏是我的代碼:使用viewpager與radiogroup在片段之間切換
Viewpager適配器:
public class ViewPagerAdapter extends FragmentPagerAdapter {
public static int int_items = 3;
public ViewPagerAdapter(FragmentManager fm) {
super(fm);
}
@Override
public Fragment getItem(int position) {
switch (position) {
case 0:
return new WelcomeOneFragment();
case 1:
return new WelcomeTwoFragment();
case 2:
return new WelcomeThreeFragment();
}
return null;
}
@Override
public int getCount() {
return int_items;
}
片段與RadioGroup中:
public class TabFragment extends BaseFragment implements ViewPager.OnPageChangeListener, View.OnClickListener {
public static ViewPager mViewPager;
private Button mButtonMassage;
private RadioGroup mRadioGroup;
public static TabFragment newInstance() {
return new TabFragment();
}
@Nullable
@Override
public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_tab, container, false);
initUi(rootView);
return rootView;
}
@Override
public void initUi(View rootView) {
mRadioGroup = (RadioGroup) rootView.findViewById(R.id.radio_group);
mViewPager = (ViewPager) rootView.findViewById(R.id.view_pager);
mButtonMassage = (Button) rootView.findViewById(R.id.buttonMassage);
initListeners();
}
@Override
public void initListeners() {
mButtonMassage.setOnClickListener(this);
mViewPager.addOnPageChangeListener(this);
initData();
}
@Override
public void initData() {
mViewPager.setAdapter(new ViewPagerAdapter(getChildFragmentManager()));
mViewPager.setCurrentItem(0);
}
@Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.buttonMassage:
Intent i = new Intent(getActivity(), MassageActivity.class);
startActivity(i);
break;
default:
break;
}
}
@Override
public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
}
@Override
public void onPageSelected(int position) {
mRadioGroup.check(mRadioGroup.getChildAt(position).getId());
}
@Override
public void onPageScrollStateChanged(int state) {
}
}