首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >setText in CustomPagerAdapter

setText in CustomPagerAdapter
EN

Stack Overflow用户
提问于 2015-11-30 21:22:09
回答 1查看 123关注 0票数 0

这是我的自定义ViewPager适配器。我试图将每个页面的标题设置为TextView,这与ViewPager的位置有关。为什么这不管用?

代码语言:javascript
复制
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);
    }
}

我一直收到以下错误:

代码语言:javascript
复制
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]);

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2015-11-30 21:43:28

不要紧。我将TextView添加到pager_item.xml中,就像j2emanue正确地暗示的那样。以前,我的TextView位于ViewPager所在的页面布局中,这是不正确的。

代码语言:javascript
复制
<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>
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/34008231

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档