viewpager动态添加小圆点

时间:2021-02-12 20:41:29
<span style="font-size:18px;"><pre name="code" class="java"><span style="font-size:18px;">private void editBanner(ViewHolder itemViewHolder) {
        View itemView = itemViewHolder.itemView;
        ViewPager viewPager = (ViewPager) itemView.findViewById(R.id.pager_banner);
        AQuery aq = new AQuery(viewPager);
        double ratio = DensityUtil.getRatio(fragment.getActivity());
        float w = (float) (1080.0 * ratio);
        float h = (float) (400.0 * ratio);
        aq.id(viewPager).width((int) w, false).height((int) h, false);
        viewPager.setAdapter(new BannerAdapter(fragment.getActivity()));
        viewPager.setOnTouchListener(this);
        viewPager.addOnPageChangeListener(this);

        old_position = 0;
        linearLayout = (LinearLayout) itemView.findViewById(R.id.ll_banner);
        for (int i = 0; i < 5; i++) {
            ImageView imageView = new ImageView(fragment.getActivity());
            imageView.setImageResource(R.drawable.banner_dot_off);
            imageView.setTag("" + i);
            linearLayout.addView(imageView);
            aq.id(imageView).margin(4, 0, 4, 8);
        }
        ImageView imageView = (ImageView) linearLayout.findViewWithTag("0");
        imageView.setImageResource(R.drawable.banner_dot_on);
    }</span></span>


 
<span style="font-size:18px;"><span style="font-size:18px;">
</span></span>
<span style="font-size:18px;"><span style="font-size:18px;"><span style="font-size:18px;">public void onPageSelected(int position) {
        //new
        ImageView imageView = (ImageView) linearLayout.findViewWithTag("" + position);
        imageView.setImageResource(R.drawable.banner_dot_on);
        //old
        ImageView old_imageView = (ImageView) linearLayout.findViewWithTag("" + old_position);
        old_imageView.setImageResource(R.drawable.banner_dot_off);
        old_position = position;
    }</span></span></span>

小圆点xml

dot_on

<span style="font-size:18px;"><?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"
    android:shape="oval">

    <solid android:color="@color/banner_dot_on" />

    <size
        android:width="6dp"
        android:height="6dp" />
</shape></span>

dot_off

<span style="font-size:18px;"><?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"
    android:shape="oval">

    <solid android:color="@color/banner_dot_off" />

    <size
        android:width="6dp"
        android:height="6dp" />
</shape></span>