这是我的自定义ViewPager适配器。我试图将每个页面的标题设置为TextView,这与ViewPager的位置有关。为什么这不管用?
public class CustomPagerAdapter extends PagerAdapter {
private int[] image_resources = {
android.R.color.transparent,
R.drawable.image1,
};
private String[] title_resources = {
"",
"Title #1",
};
private Context ctx;
private LayoutInflater layoutInflater;
public CustomPagerAdapter(Context ctx) {
this.ctx = ctx;
}
@Override
public int getCount() {
return image_resources.length;
}
@Override
public boolean isViewFromObject(View view, Object o) {
return (view == (RelativeLayout) o);
}
@Override
public Object instantiateItem(ViewGroup container, int position) {
layoutInflater = (LayoutInflater) ctx.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View item_view = layoutInflater.inflate(R.layout.pager_item, container, false);
ImageView imageview = (ImageView) item_view.findViewById(R.id.image_view);
imageview.setImageResource(image_resources[position]);
TextView title = (TextView) item_view.findViewById(R.id.title_view);
title.setText(title_resources[position]);
container.addView(item_view);
return item_view;
}
@Override
public void destroyItem(ViewGroup container, int position, Object object) {
container.removeView((RelativeLayout) object);
}
}我一直收到以下错误:
java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.TextView.setText(java.lang.CharSequence)' on a null object reference
at com.app.feed.CustomPagerAdapter.instantiateItem(CustomPagerAdapter.java:114)这个错误肯定是在下面一行抛出的:title.setText(title_resources[position]);
发布于 2015-11-30 21:43:28
不要紧。我将TextView添加到pager_item.xml中,就像j2emanue正确地暗示的那样。以前,我的TextView位于ViewPager所在的页面布局中,这是不正确的。
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<ImageView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="@+id/image_view"
android:scaleType="centerCrop" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceLarge"
android:id="@+id/title_view"
android:layout_centerHorizontal="true" />
</RelativeLayout>https://stackoverflow.com/questions/34008231
复制相似问题