【江鸟中原】鸿蒙移动开发—广告图片轮播
  BorZTNdvJVVf 2023年12月23日 16 0

我是中原工学院的学生,我的鸿蒙大作业如下

一.运行效果示意图

【江鸟中原】鸿蒙移动开发—广告图片轮播_sed



【江鸟中原】鸿蒙移动开发—广告图片轮播_ide_02


【江鸟中原】鸿蒙移动开发—广告图片轮播_Image_03

二.代码实现

1.主界面实现:

package com.huawei.mytestapp;

import com.huawei.mytestapp.slice.MainAbilitySlice;
import ohos.aafwk.ability.Ability;
import ohos.aafwk.content.Intent;

public class MainAbility extends Ability {
    @Override
    public void onStart(Intent intent) {
        super.onStart(intent);
        super.setMainRoute(MainAbilitySlice.class.getName());
    }
}
public class GlideImageLoader extends ImageLoader {
    @Override
    public void displayImage(Context context, Object path, Image imageView) {

        Glide.with(context)
                .load(path)
                .placeholder(ResourceTable.Media_no_banner)
                .diskCacheStrategy(DiskCacheStrategy.ALL)
                .skipMemoryCache(true)
                .into(imageView);
    }
}
public abstract class ImageLoader implements ImageLoaderInterface<Image> {

    public ImageLoader() {
    }

    public Image createImageView(Context context) {
        Image imageView = new Image(context);
        return imageView;
    }
    package com.youth.banner.loader;


import ohos.agp.components.Component;
import ohos.app.Context;

import java.io.Serializable;


public interface ImageLoaderInterface<T extends Component> extends Serializable {

    void displayImage(Context context, Object path, T imageView);

    T createImageView(Context context);
}
package com.youth.banner.listener;


/**
 * 旧版接口,由于返回的下标是从1开始,下标越界而废弃(因为有人使用所以不能直接删除)
 */
@Deprecated
public interface OnBannerClickListener {
    public void OnBannerClick(int position);
}
package com.youth.banner.listener;

public interface OnBannerListener {
    public void OnBannerClick(int position);
}
package com.huawei.mytestapp;

import ohos.aafwk.ability.AbilityPackage;



public class MyApplication extends AbilityPackage {
    @Override
    public void onInitialize() {
        super.onInitialize();
    }
}

2.创建横幅类

public class WeakHandler {
    private final EventHandler mExec;
    private Lock mLock = new ReentrantLock();
    @SuppressWarnings("ConstantConditions")
    final ChainedRef mRunnables = new ChainedRef(mLock, null);



    public WeakHandler( EventRunner eventRunner) {
        mExec = new EventHandler(eventRunner);
    }

//    /**
//     * Use the provided {@link Looper} instead of the default one and take a callback
//     * interface in which to handle messages.
//     *
//     * @param looper The looper, must not be null.
//     * @param callback The callback interface in which to handle messages, or null.
//     */
//    public WeakHandler(@NonNull Looper looper, @NonNull Handler.Callback callback) {
//        mCallback = callback;
//        mExec = new ExecHandler(looper, new WeakReference<>(callback));
//    }

    /**
     * Causes the Runnable r to be added to the message queue.
     * The runnable will be run on the thread to which this handler is
     * attached.
     *
     * @param r The Runnable that will be executed.
     *
     * @return Returns true if the Runnable was successfully placed in to the
     *         message queue.  Returns false on failure, usually because the
     *         looper processing the message queue is exiting.
     */
    public final void post( Runnable r) {
         mExec.postTask(wrapRunnable(r));
    }



    public final void postAtTime(Runnable r, long uptimeMillis) {
         mExec.postTimingTask(wrapRunnable(r), uptimeMillis);
    }


    public final void  postAtTime(Runnable r, Object token, long uptimeMillis) {
        mExec.postTimingTask(wrapRunnable(r),  uptimeMillis, (EventHandler.Priority) token);
    }

    /**
     * Causes the Runnable r to be added to the message queue, to be run
     * after the specified amount of time elapses.
     * The runnable will be run on the thread to which this handler
     * is attached.
     *
     * @param r The Runnable that will be executed.
     * @param delayMillis The delay (in milliseconds) until the Runnable
     *        will be executed.
     *
     * @return Returns true if the Runnable was successfully placed in to the
     *         message queue.  Returns false on failure, usually because the
     *         looper processing the message queue is exiting.  Note that a
     *         result of true does not mean the Runnable will be processed --
     *         if the looper is quit before the delivery time of the message
     *         occurs then the message will be dropped.
     */
    public final void postDelayed(Runnable r, long delayMillis) {
         mExec.postTask(wrapRunnable(r),delayMillis);
    }

    /**
     * Posts a message to an object that implements Runnable.
     * Causes the Runnable r to executed on the next iteration through the
     * message queue. The runnable will be run on the thread to which this
     * handler is attached.
     * <b>This method is only for use in very special circumstances -- it
     * can easily starve the message queue, cause ordering problems, or have
     * other unexpected side-effects.</b>
     *
     * @param r The Runnable that will be executed.
     *
     * @return Returns true if the message was successfully placed in to the
     *         message queue.  Returns false on failure, usually because the
     *         looper processing the message queue is exiting.
     */
    public final void postAtFrontOfQueue(Runnable r) {
         mExec.postTask(wrapRunnable(r));
    }

    /**
     * Remove any pending posts of Runnable r that are in the message queue.
     */
    public final void removeCallbacks(Runnable r) {
        final WeakRunnable runnable = mRunnables.remove(r);
        if (runnable != null) {
            mExec.removeTask(runnable);
        }
    }

    /**
     * Remove any pending posts of Runnable <var>r</var> with Object
     * <var>token</var> that are in the message queue.  If <var>token</var> is null,
     * all callbacks will be removed.
     */
    public final void removeCallbacks(Runnable r, Object token) {
        final WeakRunnable runnable = mRunnables.remove(r);
        if (runnable != null) {
            mExec.removeEvent(0,runnable);
        }
    }

    /**
     * Pushes a message onto the end of the message queue after all pending messages
     * before the current time. It will be received in callback,
     * in the thread attached to this handler.
     *
     * @return Returns true if the message was successfully placed in to the
     *         message queue.  Returns false on failure, usually because the
     *         looper processing the message queue is exiting.
     */
    public final void sendMessage(InnerEvent msg) {
         mExec.sendEvent(msg);
    }

    /**
     * Sends a Message containing only the what value.
     *
     * @return Returns true if the message was successfully placed in to the
     *         message queue.  Returns false on failure, usually because the
     *         looper processing the message queue is exiting.
     */
    public final void sendEmptyMessage(int what) {
         mExec.sendEvent(what);
    }


    public final void sendEmptyMessageDelayed(int what, long delayMillis) {
         mExec.sendEvent(what, delayMillis);
    }


    public final void sendEmptyMessageAtTime(int what, long uptimeMillis) {
         mExec.sendTimingEvent(what, uptimeMillis);
    }

    /**
     * Enqueue a message into the message queue after all pending messages
     * before (current time + delayMillis). You will receive it in
     * callback, in the thread attached to this handler.
     *
     * @return Returns true if the message was successfully placed in to the
     *         message queue.  Returns false on failure, usually because the
     *         looper processing the message queue is exiting.  Note that a
     *         result of true does not mean the message will be processed -- if
     *         the looper is quit before the delivery time of the message
     *         occurs then the message will be dropped.
     */
    public final void sendMessageDelayed(InnerEvent msg, long delayMillis) {
         mExec.sendEvent(msg, delayMillis);
    }


    public void sendMessageAtTime(InnerEvent msg, long uptimeMillis) {
         mExec.sendTimingEvent(msg, uptimeMillis);
    }

    /**
     * Enqueue a message at the front of the message queue, to be processed on
     * the next iteration of the message loop.  You will receive it in
     * callback, in the thread attached to this handler.
     * <b>This method is only for use in very special circumstances -- it
     * can easily starve the message queue, cause ordering problems, or have
     * other unexpected side-effects.</b>
     *
     * @return Returns true if the message was successfully placed in to the
     *         message queue.  Returns false on failure, usually because the
     *         looper processing the message queue is exiting.
     */
    public final void sendMessageAtFrontOfQueue(InnerEvent msg) {
         mExec.sendEvent(msg);
    }

    /**
     * Remove any pending posts of messages with code 'what' that are in the
     * message queue.
     */
    public final void removeMessages(int what) {
        mExec.removeEvent(what);
    }

    /**
     * Remove any pending posts of messages with code 'what' and whose obj is
     * 'object' that are in the message queue.  If <var>object</var> is null,
     * all messages will be removed.
     */
    public final void removeMessages(int what, Object object) {
        mExec.removeEvent(what, object);
    }

    /**
     * Remove any pending posts of callbacks and sent messages whose
     * <var>obj</var> is <var>token</var>.  If <var>token</var> is null,
     * all callbacks and messages will be removed.
     */
    public final void removeCallbacksAndMessages(Object token) {
        mExec.removeAllEvent();
    }

    /**
     * Check if there are any pending posts of messages with code 'what' in
     * the message queue.
     */
    public final boolean hasMessages(int what) {
        return mExec.hasInnerEvent(what);
    }

    /**
     * Check if there are any pending posts of messages with code 'what' and
     * whose obj is 'object' in the message queue.
     */
    public final boolean hasMessages(int what, Object object) {
        return mExec.hasInnerEvent( object);
    }

    public final EventRunner geteventrunner() {
        return mExec.getEventRunner();
    }

    private WeakRunnable wrapRunnable( Runnable r) {
        //noinspection ConstantConditions
        if (r == null) {
            throw new NullPointerException("Runnable can't be null");
        }
        final ChainedRef hardRef = new ChainedRef(mLock, r);
        mRunnables.insertAfter(hardRef);
        return hardRef.wrapper;
    }

//    private static class ExecHandler extends EventHandler {
////        private final WeakReference<Handler.Callback> mCallback;
//
//        ExecHandler() {
//            mCallback = null;
//        }
//
//        ExecHandler(WeakReference<Handler.Callback> callback) {
//            mCallback = callback;
//        }
//
//        ExecHandler(Looper looper) {
//            super(looper);
//            mCallback = null;
//        }
//
//        ExecHandler(Looper looper, WeakReference<Handler.Callback> callback) {
//            super(looper);
//            mCallback = callback;
//        }
//
//        public ExecHandler(EventRunner eventRunner) {
//        }
//
//        @Override
////        public void handleMessage(@NonNull Message msg) {
////            if (mCallback == null) {
////                return;
////            }
////            final Handler.Callback callback = mCallback.get();
////            if (callback == null) { // Already disposed
////                return;
////            }
////            callback.handleMessage(msg);
////        }
////    }

    static class WeakRunnable implements Runnable {
        private final WeakReference<Runnable> mDelegate;
        private final WeakReference<ChainedRef> mReference;

        WeakRunnable(WeakReference<Runnable> delegate, WeakReference<ChainedRef> reference) {
            mDelegate = delegate;
            mReference = reference;
        }

        @Override
        public void run() {
            final Runnable delegate = mDelegate.get();
            final ChainedRef reference = mReference.get();
            if (reference != null) {
                reference.remove();
            }
            if (delegate != null) {
                delegate.run();
            }
        }
    }

    static class ChainedRef {

        ChainedRef next;

        ChainedRef prev;

        final Runnable runnable;

        final WeakRunnable wrapper;


        Lock lock;

        public ChainedRef(Lock lock, Runnable r) {
            this.runnable = r;
            this.lock = lock;
            this.wrapper = new WeakRunnable(new WeakReference<>(r), new WeakReference<>(this));
        }

        public WeakRunnable remove() {
            lock.lock();
            try {
                if (prev != null) {
                    prev.next = next;
                }
                if (next != null) {
                    next.prev = prev;
                }
                prev = null;
                next = null;
            } finally {
                lock.unlock();
            }
            return wrapper;
        }

        public void insertAfter( ChainedRef candidate) {
            lock.lock();
            try {
                if (this.next != null) {
                    this.next.prev = candidate;
                }

                candidate.next = this.next;
                this.next = candidate;
                candidate.prev = this;
            } finally {
                lock.unlock();
            }
        }


        public WeakRunnable remove(Runnable obj) {
            lock.lock();
            try {
                ChainedRef curr = this.next; // Skipping head
                while (curr != null) {
                    if (curr.runnable == obj) { // We do comparison exactly how Handler does inside
                        return curr.remove();
                    }
                    curr = curr.next;
                }
            } finally {
                lock.unlock();
            }
            return null;
        }
    }

三.使用方法

setBannerStyle(int bannerStyle) 设置轮播样式(默认为CIRCLE_INDICATOR,有五种样式可以选择,其中数字样式有点小bug待修复)

isAutoPlay(boolean isAutoPlay) 设置是否自动轮播(默认自动) setViewPagerIsScroll(boolean isScroll) 设置是否允许手动滑动轮播图(默认true) update(List<?> imageUrls,List titles) 更新图片和标题 update(List<?> imageUrls) 更新图片 startAutoPlay() 开始轮播 1.4开始,此方法只作用于banner加载完毕-->需要在start()后执行 stopAutoPlay() 结束轮播 1.4开始,此方法只作用于banner加载完毕-->需要在start()后执行 start() 开始进行banner渲染(必须放到最后执行) setBannerTitles(List titles) 设置轮播要显示的标题和图片对应(如果不传默认不显示标题) setDelayTime(int time) 设置轮播图片间隔时间(单位毫秒,默认为2000) setImages(Object[]/List<?> images) 设置轮播图片(所有设置参数方法都放在此方法之前执行) setOnBannerClickListener(this) 设置点击事件,下标是从1开始 (废弃了) setOnBannerListener(this) 设置点击事件,下标是从0开始 setImageLoader(Object implements ImageLoader) 设置图片加载器 (等三方库完善可以加载网络图片)

【版权声明】本文内容来自摩杜云社区用户原创、第三方投稿、转载,内容版权归原作者所有。本网站的目的在于传递更多信息,不拥有版权,亦不承担相应法律责任。如果您发现本社区中有涉嫌抄袭的内容,欢迎发送邮件进行举报,并提供相关证据,一经查实,本社区将立刻删除涉嫌侵权内容,举报邮箱: cloudbbs@moduyun.com

  1. 分享:
最后一次编辑于 2023年12月23日 0

暂无评论

推荐阅读
  TX6np8f0LW62   2023年12月23日   28   0   0 androidciideciideandroid
BorZTNdvJVVf
最新推荐 更多