[英]All pages in android ViewPager are shown in first slide
我在布局中使用android android.support.v4.view.ViewPager
和自定義PagerAdapter
。 我以這種方式(簡化)定義了適配器:
private final PagerAdapter mPagerAdapter= new PagerAdapter() {
@Override
public void destroyItem(View v, int arg1, Object o) {
((ViewPager) v).removeView((View) o);
}
@Override
public boolean isViewFromObject(View v, Object o) {
return o == ((View) o);
}
@Override
public int getCount() {
return 2;
}
public Object instantiateItem(View collection, final int position) {
LayoutInflater inflater = (LayoutInflater) collection.getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View view = inflater.inflate(R.layout.single_page, null);
final String name;
TextView pageName = (TextView) view.findViewById(R.id.tvPageName);
switch (position) {
case 0:
name = "page 1";
break;
case 1:
name = "page 2";
break;
default:
name = "";
}
pageName.setText(name);
((ViewPager) collection).addView(view, 0);
return view;
}
};
single_page
是一種布局,該布局由包裝在LinearLayout
的文本視圖( tvPageName
)組成。
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical" >
<TextView
android:id="@+id/tvPageName"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/app_name" />
</LinearLayout>
結果如下:
我嘗試為每個頁面使用兩種不同的布局,但結果是相同的。
布局xml的一部分:
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:gravity="center_horizontal"
android:orientation="vertical" >
<FrameLayout
android:layout_width="match_parent"
android:layout_height="wrap_content" >
<android.support.v4.view.ViewPager
android:id="@+id/pages"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#ffeedd" />
</FrameLayout>
</LinearLayout>
您對isViewFromObject()
是錯誤的。 當前的實現將始終返回true
,因此您的PagerAdapter將無法正常工作。
你需要它
@Override
public boolean isViewFromObject(View v, Object o) {
return v == o;
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.