Android:Slider图像viewPager没有显示任何内容

时间:2017-05-27 17:12:54

标签: java android layout android-viewpager adapter

我已经看到了与此主题相关的所有问题,但没有找到解决方案,在我的情况下,viewpager没有显示任何内容,其简单的图像滑块,而且toast出现,因为我正在交换,但没有看到图像和文本,以及我添加这些行时(如其他解决方案所述)

 ((ViewPager) container).addView(iv, 0);
 ((ViewPager) container).addView(tv, 0);

它给了我错误

  

android.support.v4.view.ViewPager $ LayoutParams无法强制转换为android.view.ViewGroup $ MarginLayoutParams

这是我的main.xml文件(内部相对布局):

<android.support.v4.view.ViewPager
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:id="@+id/view_pager"/>

这是viewPager适配器

public class ClsCustomPagerViewAdapter extends PagerAdapter {

int[] layouts;
String[] titles;
LayoutInflater layoutInflater;
Context context;

public ClsCustomPagerViewAdapter(Context context, int[] layouts, 
String[] titles) {
    this.layouts = layouts;
    this.titles = titles;
    this.context = context;
    layoutInflater = LayoutInflater.from(context);
}

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

    View imageLayout = layoutInflater.inflate(R.layout.image_placeholder
, container);
    TextView tv = (TextView) imageLayout.findViewById(R.id.tv);
    ImageView iv = (ImageView) imageLayout.findViewById(R.id.iv);
    Toast.makeText(context,
            "Viewpagers " + titles[position] ,
            Toast.LENGTH_SHORT).show();

    tv.setText(titles[position]);
    iv.setImageResource(layouts[position]);

    ((ViewPager) container).addView(iv, 0);
    ((ViewPager) container).addView(tv, 0);
    return imageLayout;
}

@Override
public int getCount() {
    return layouts.length;
}

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

这是viewpager适配器的图像和textviews布局(在framelayout内部)

    <TextView
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:id="@+id/tv"
    android:text="Hello world"
    android:gravity="center_horizontal"
    android:layout_marginTop="20dp"
    android:layout_alignTop="@+id/iv"
    android:layout_alignBottom="@+id/iv"
    android:layout_alignLeft="@+id/iv"
    android:layout_alignRight="@+id/iv"/>

<ImageView
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:id="@+id/iv"
    />

1 个答案:

答案 0 :(得分:2)

替换这两行代码

((ViewPager) container).addView(iv, 0);
((ViewPager) container).addView(tv, 0);

container.addView(imageLayout);

<强>编辑:

另外

View imageLayout = layoutInflater.inflate(R.layout.image_placeholder
, container);

View imageLayout = layoutInflater.inflate(R.layout.image_placeholder
, container, false);