在ViewPager中更改ImageView Drawable

时间:2016-08-09 11:04:40

标签: android android-layout android-fragments android-viewpager

所以,我有一个ViewPager inside it的片段。我想通过片段更改ViewPager中的布局图像。

为此,我编写了以下代码:

public View onCreateView(LayoutInflater inflater,  ViewGroup container, Bundle savedInstanceState) {
    v = inflater.inflate(R.layout.fragment_tab,container,false); //fragment layout
    imageLayout = inflater.inflate(R.layout.view_image, null, false); //layout that's used in viewPager
    theImage = (ImageView) imageLayout .findViewById(R.id.image); //getting the ImageView

    ViewPager viewPager = (ViewPager) v.findViewById(R.id.resultImagesPager);
    viewPager.setAdapter(new ResultImageAdapter(getActivity()));
    }

代码本身不会崩溃我的应用程序,但无论我写什么,我都无法更改ImageView的位图

2 个答案:

答案 0 :(得分:1)

您应该在ViewPager适配器内更改drawable 在这种情况下,您的适配器可能如下所示:

    private List<YourObject> mList;
    // pass list of items into constructor
    public CustomPagerAdapter(Context context, List<YourObject> list) {
        mContext = context;
        mList = list;
    }

    @Override
    public Object instantiateItem(ViewGroup collection, int position) {
        CustomPagerEnum customPagerEnum = CustomPagerEnum.values()[position];
        LayoutInflater inflater = LayoutInflater.from(mContext);
        ViewGroup layout = (ViewGroup) inflater.inflate(customPagerEnum.getLayoutResId(), collection, false);
        // get corresponding object and retrieve needed drawable
        YourObject yourObject = mList.get(position);
        ImageView theImage = (ImageView) layout.findViewById(R.id.image);
        theImage.setImageDrawable(yourObject.getYourDravwable());

        collection.addView(layout);
        return layout;
    }

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

...

并在你的片段中:

List<YourObject> list = new ArrayList<>();
// add your objects or whatever
list.add(new YourObject(name, drawable);
viewPager.setAdapter(new ResultImageAdapter(getActivity(), list));

答案 1 :(得分:0)

在这一行中你只需要创建R.layout.view_image的新实例,而这个创建的视图没有添加到任何容器上

imageLayout = inflater.inflate(R.layout.view_image, null, false);