我尝试使用滑动图像制作简单的应用程序。我用这篇文章http://www.androidbegin.com/tutorial/android-viewpager-gallery-images-and-texts-tutorial/ .
这是我的带有 viewpager 的 xml: 主.xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="horizontal" >
<android.support.v4.view.ViewPager
android:id="@+id/pages"
android:layout_height="match_parent"
android:layout_width="match_parent">
</android.support.v4.view.ViewPager>
</LinearLayout>
这是我的带有图像的 xml: 项目.xml
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent" >
<ImageView
android:id="@+id/image"
android:layout_gravity="center"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:src="@drawable/ic_launcher" />
</RelativeLayout>
这是我的适配器: ViewerPagerAdapter.java
public class ViewerPagerAdapter extends PagerAdapter {
private Context mContext;
private ArrayList<CueModel> mArray;
private LayoutInflater mInflater;
private ImageView mImage;
public ViewerPagerAdapter(Context _context){
mContext = _context;
mInflater = (LayoutInflater) mContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
public void setArray(ArrayList<Bitmap> arr){
mArray = arr;
}
@Override
public int getItemPosition(Object object) {
return POSITION_NONE;
}
@Override
public Object instantiateItem(ViewGroup container, int position) {
View itemView = mInflater.inflate(R.layout.item, container, false);
mImage = (ImageView)itemView.findViewById(R.id.image);
mImage.setImageBitmap(mArray.get(position));
container.addView(itemView);
return itemView;
}
@Override
public int getCount() {
return mArray.size();
}
@Override
public void destroyItem(ViewGroup container, int position, Object object) {
container.removeView((View)object);
}
@Override
public boolean isViewFromObject(View arg0, Object arg1) {
return arg0.equals(arg1);
}
这是我的 Activity : OneActivity.java (充满图像的 mArrays)
public class OneActivity extends Activity {
ArrayList<Bitmap> mArrays;
ViewerPagerAdapter mAdapter;
ViewPager mPager;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main.xml);
mPager = (ViewPager) findViewById(R.id.pages);
mAdapter = new ViewerPagerAdapter(OneActivity.this);
mAdapter.setArrays(mArrays);
mPager.setAdapter(mAdapter);
}
}
我不明白我做错了什么。 instantiateItem 不调用。
PS.我的应用和
之间的区别文章我有一些 Activity (我的数组列表由项目初始化) 谢谢
最佳答案
#instantiateItem()
在 ViewPager 需要新 View 时调用。最初,如果适配器的 getCount() > 0
,它将为中间的 View 和右侧的 View 调用 #instantiateItem()
两次。这就是为什么每次更改数组时都需要在 #setArray()
方法中调用 #notifyDataSetChanged()
的原因。您还需要在每次从列表中添加或删除项目时调用它。如果您的数组在 #onCreate()
中为空,则 #getCount() == 0
因此 ViewPager 认为它是空的并且不会打扰。
关于java - 为什么 instantiateItem 不调用,ViewPager 不工作?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25292224/