在我的MainActivity中,我有以下代码:
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.view.ViewPager;
public class MainActivity extends FragmentActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
myViewPager.setCurrentItem(1);
ViewPager pager = (ViewPager) findViewById(R.id.viewPager);
pager.setAdapter(new MyPagerAdapter(getSupportFragmentManager()));
}
private class MyPagerAdapter extends FragmentPagerAdapter {
public MyPagerAdapter(FragmentManager fm) {
super(fm);
}
@Override
public Fragment getItem(int pos) {
switch(pos) {
case 2: return FirstFragment.newInstance("FirstFragment, Instance 1");
case 1: return SecondFragment.newInstance("SecondFragment, Instance 1");
case 0: return ThirdFragment.newInstance("ThirdFragment, Instance 1");
default: return ThirdFragment.newInstance("ThirdFragment, Default");
}
}
@Override
public int getCount() {
return 3;
}
}
}
这些片段工作正常,当我运行MainActivity时,我想先打开SecondFragment,所以我尝试使用:
myViewPager.setCurrentItem(1);
但是然后我收到错误“ myViewPager无法解决”,我尝试更新SDK和添加支持库,但似乎无济于事,不知道该如何解决?
最佳答案
您尚未声明myViewPager
,还需要在myViewPager.setCurrentItem(1);
之前对其进行初始化。
您可能是说pager.setCurrentItem(1);