如何将列表从片段发送到 android 中的自定义视图 class?

How to send list from a fragment to a custom view class in android?

我创建了一个片段,我想从中将列表发送到自定义视图class我该如何发送它。我曾尝试使用自定义 class 构造函数,但它给出了错误。对这个问题有什么建议吗?

public class BannerSliderView extends FrameLayout {

private ViewPager viewPager;
private PageIndicatorView pageIndicatorView;
private List<Banner> bannersList;
private BannerViewPagerAdapter bannerViewPagerAdapter;
public BannerSliderView(@NonNull Context context) {
    this(context, null);
}

public BannerSliderView(@NonNull Context context, @Nullable AttributeSet attrs) {
    this(context, attrs, -1);
}

public BannerSliderView(@NonNull Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
    super(context, attrs, defStyleAttr);
    init();
}

private void init() {
    View view = View.inflate(getContext(), R.layout.banner_slider_layout, null);
    addView(view);
    bannersList=new ArrayList<>();
    viewPager = view.findViewById(R.id.viewPager);
    viewPager.setPageMargin(valueInPixels);
    pageIndicatorView = view.findViewById(R.id.pager_indicator);
    bannerViewPagerAdapter=new 
    BannerViewPagerAdapter(getContext(),bannersList);
    viewPager.setAdapter(bannerViewPagerAdapter);
    pageIndicatorView.setViewPager(viewPager);
    
}
public void setBannersList(List<Banner> bannersList) {
    this.bannersList = bannersList;
}

主页片段

public class HomeFragment {
    bannerSliderView=view.findViewById(R.id.BannerSliderView);
    Banner banner = new Banner("Promotion", "Noor Designer", String.valueOf(R.drawable.loginbackground));
    bannerList.add(banner);
    bannerList.add(banner);
    bannerList.add(banner);
    bannerSliderView.setBannersList(bannerList);
}

您需要使 View 无效,因为您的数据是动态的,您可以在设置数据后执行其中的所有操作。下面是一个应该有效的例子。

public class BannerSliderView extends FrameLayout {
private ViewPager viewPager;
private PageIndicatorView pageIndicatorView;
private List<Banner> bannersList;
private BannerViewPagerAdapter bannerViewPagerAdapter;
public BannerSliderView(@NonNull Context context) {
    this(context, null);
}

public BannerSliderView(@NonNull Context context, @Nullable AttributeSet attrs) {
    this(context, attrs, -1);
}

public BannerSliderView(@NonNull Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
    super(context, attrs, defStyleAttr);
    init();
}

private void init() {
    View view = View.inflate(getContext(), R.layout.banner_slider_layout, null);
    viewPager = view.findViewById(R.id.viewPager);
    viewPager.setPageMargin(valueInPixels);
    pageIndicatorView = view.findViewById(R.id.pager_indicator);
    addView(view);
}

public void setBannersList(List<Banner> bannersList) {
    this.bannersList = bannersList;
    bannerViewPagerAdapter = new
            BannerViewPagerAdapter(getContext(), bannersList);
    viewPager.setAdapter(bannerViewPagerAdapter);
    pageIndicatorView.setViewPager(viewPager);
}
}

通过这种方法,bannerViewPagerAdapter 将在任何调用 setBannersList 之前成为 null。或者您可以只在 #init 中设置适配器并只更新 setBannersList.

中的数据