2017-05-27 150 views
0

我已经看到所有与此主题有关的问题,但没有找到解决方案,在我的情况下viewpager没有显示任何东西,其简单的图像滑块,而且吐司出现,米swaping但没看到图片和文字,而当IM加上几行(其它解决方案表示)Android:滑块图像viewPager没有显示任何东西

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

它给了我错误

android.support.v4.view.ViewPager$LayoutParams cannot be cast to 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); 
} 

并且这对于图像和textviews为viewpager适配器布局(内侧的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

替换的这两行代码

((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); 
+0

现在,它的说法:java.lang.StackOverflowError的:堆栈大小8MB – blackHawk

+0

就是传递null之间的区别容器膨胀 – blackHawk

+0

对不起,我可能已经给你从我的应用程序的旧代码。我刚刚阅读了这篇文章,解释了这个问题。链接在这里。去检查一下。 https://possiblemobile.com/2013/05/layout-inflation-as-intended/ –