我有一个使用以下适配器的viewpager,在加载后,第一个视图显示为空,但事实并非如此.如果我滚动到下一个视图,然后向后滚动,我可以看到内容.
@H_502_2@import android.content.Context;
import android.os.Parcelable;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.view.View;
import android.widget.TextView;
import java.util.ArrayList;
public class MyPagerAdapter extends PagerAdapter {
Context context;
public ArrayList<TextView> mViews;
int layoutResourceId;
public MyPagerAdapter(Context context) {
mViews = new ArrayList<TextView>();
}
@Override
public void destroyItem(View view,int arg1,Object object) {
((ViewPager)view).removeView((View)object);
}
@Override
public void finishUpdate(View arg0) {
}
@Override
public int getCount() {
return mViews.size();
}
@Override
public Object instantiateItem(View view,int position) {
View myView = mViews.get(position);
((ViewPager)view).addView(myView);
return myView;
}
@Override
public boolean isViewFromObject(View view,Object object) {
return view == object;
}
@Override
public void restoreState(Parcelable arg0,ClassLoader arg1) {
}
@Override
public Parcelable saveState() {
return null;
}
@Override
public void startUpdate(View arg0) {
}
@Override
public int getItemPosition(Object object) {
return POSITION_NONE;
}
}
以下是从我的活动中实现它的代码……
@H_502_2@public void resetPages() { if (mPageText == null) return; mPagerAdapter.mViews.clear(); for (int i = 0; i < mPageText.size(); i++) { TextView tv = new TextView(this); tv.setTextSize(mSelectedFontSize); tv.setText(mPageText.get(i)); tv.setId(i); tv.setTag(i); tv.invalidate(); mPagerAdapter.mViews.add(tv); } mPagerAdapter.notifyDataSetChanged(); mViewPager.refreshDrawableState(); }解决方法
尝试添加followind onCreate方法,我的代码工作(“TEXT 0”出现在启动时).也许只是因为在不合适的时间调用resetPages()?
@H_502_2@public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mPageText = new LinkedList<CharSequence>();
for (int i=0; i<10; i++) {
mPageText.add("TEXT "+i);
}
this.mPagerAdapter = new MyPagerAdapter(this);
this.mViewPager = (ViewPager)this.findViewById(R.id.viewpager);
this.mViewPager.setAdapter(mPagerAdapter);
resetPages();
}