gpt4 book ai didi

android - 在 ViewPager 中更改 ImageView Drawable

转载 作者:行者123 更新时间:2023-11-30 01:06:13 26 4
gpt4 key购买 nike

所以,我有一个带有 ViewPager inside it 的 fragment .我想通过 fragment 更改 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 的位图

最佳答案

您应该更改 ViewPager 适配器内部的可绘制对象。
在这种情况下,您的适配器可能如下所示:

    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();
}

...

在你的 fragment 中:

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

关于android - 在 ViewPager 中更改 ImageView Drawable,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38849015/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com