我用它来介绍用户应用程序及其功能。但是,当我运行应用程序时,片段不会以正确的顺序呈现(welcome1 - > welcome2 - > welcome3等)。相反,当向右滑动时,它会显示“welcome2,welcome 2,welcome 3,welcome 4”。当我向左滑动时,订单再次搞砸了,每次都显示“welcome4”。我的代码如下:
IntroActivity类:
public class IntroActivity extends AppCompatActivity {
private SectionsPagerAdapter mSectionsPagerAdapter;
private ViewPager mViewPager;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_feature);
mSectionsPagerAdapter = new SectionsPagerAdapter(getSupportFragmentManager());
mViewPager = (ViewPager) findViewById(R.id.container);
mViewPager.setAdapter(mSectionsPagerAdapter);
}
public class SectionsPagerAdapter extends FragmentPagerAdapter {
public SectionsPagerAdapter(FragmentManager fm) {
super(fm);
}
@Override
public Fragment getItem(int position) {
if (position == 0) {
Log.e("---","Position 0");
return WelcomeFragment.newInstance("testtitle#1",R.layout.fragment_welcome_one,R.id.welcome1);
}else if (position == 1){
Log.e("---","Position 1");
return WelcomeFragment.newInstance("testtitle#2", R.layout.fragment_welcome_two, R.id.welcome2);
}else if (position == 2){
Log.e("---","Position 2");
return WelcomeFragment.newInstance("testtitle#3", R.layout.fragment_welcome_three, R.id.welcome3);
}else if (position == 3){
Log.e("---","Position 3");
return WelcomeFragment.newInstance("testtitle#4", R.layout.fragment_welcome_four, R.id.welcome4);
}
return null;
}
@Override
public int getCount() {
return 4;
}
}
}
WelcomeFragment类:
public class WelcomeFragment extends Fragment {
static String mTitle;
static int mLayoutID;
static int mTitleID;
public WelcomeFragment() {
}
public static WelcomeFragment newInstance(String title, int layoutID, int titleID) {
WelcomeFragment mWelcomeFragment = new WelcomeFragment();
mTitle = title;
mLayoutID = layoutID;
mTitleID = titleID;
return mWelcomeFragment;
}
@Nullable
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View rootView = inflater.inflate(mLayoutID,container,false);
TextView textView = (TextView)rootView.findViewById(mTitleID);
Typeface font = Typeface.createFromAsset(getActivity().getAssets(), "fonts/Roboto-Thin.ttf");
textView.setText(mTitle);
textView.setTypeface(font);
return rootView;
}
}
我无法确定导致我的碎片绘制错误的原因,任何帮助都表示赞赏。
答案 0 :(得分:0)
您的newInstance方法以及静态成员变量不正确。
使变量成为私有而非静态
private String mTitle;
private int mLayoutID;
private int mTitleID;
并将newInstance方法更改为
public static WelcomeFragment newInstance(String title, int layoutID, int titleID) {
WelcomeFragment mWelcomeFragment = new WelcomeFragment();
mWelcomeFragment.mTitle = title;
mWelcomeFragment.mLayoutID = layoutID;
mWelcomeFragment.mTitleID = titleID;
return mWelcomeFragment;
}
考虑查看my tutorial以获取有关使用视图寻呼机的深入说明以及GitHub上的工作示例。