ViewPager未显示自定义视图

时间:2017-08-24 00:09:25

标签: java android android-viewpager android-pageradapter

正如标题所说,ViewPager没有显示它应该的内容。我一直在寻找解决方案,但没有一个能够解决问题。也许你们可以帮助我。提前谢谢!

我想将自定义视图动态添加到适配器,因为视图与数据库中的数据异步。

自定义PagerAdapter

public class SlidePagerAdapter extends PagerAdapter {

    private Context mContext;
    private List<CardView> mCards;

    public SlidePagerAdapter(Context context) {
        mContext = context;
        mCards = new ArrayList<>();
    }

    @Override
    public int getCount() {
        return mCards.size();
    }

    @Override
    public int getItemPosition (Object object) {
        int index = mCards.indexOf(object);
        if (index == -1)
            return POSITION_NONE;
        else
            return index;
    }

    @Override
    public Object instantiateItem(ViewGroup container, int position) {
        View v = mCards.get(position);
        container.addView(v);
        return container;
    }

    @Override
    public void destroyItem (ViewGroup container, int position, Object object) {
        container.removeView(mCards.get(position));
    }

    @Override
    public boolean isViewFromObject(View view, Object object) {
        return view == object;
    }

    public void add(Card card) {
        mCards.add(new CardView(mContext, card));
    }

    public void addAll(List<Card> cards) {
        for (Card card : cards) {
            add(card);
        }
    }

    public void clear() {
        mShopcards.clear();
    }
}

自定义视图已成功生成并保存在适配器的列表中,但它们未显示在ViewPager中...

1 个答案:

答案 0 :(得分:1)

检查一下:

@Override 
public boolean isViewFromObject(View view, Object object) { 
return view == object; 
}

你无法比较2.视图是对象的孩子。

    @Override 
public Object instantiateItem(ViewGroup container, int position) { 
View v = mShopcards.get(position);
 container.addView(v);
 return container;
 }