鸿蒙MVP DEMO(含线程切换及Toast封装)

地址:https://github.com/chyjack/harmony-mvp

封装了一个好用的鸿蒙上的mvp框架,包含了线程切换,Toast封装及一些原Android常用的函数

线程相关工具类:


public class ThreadUtil {
    
    private volatile static ExecutorService mThreadPool;
    private volatile static EventHandler uiHandler;

    ...


    /**
     * 提供不依赖Activity Context的runOnUiThread方法
     */
    public static void runOnUiThread(Object token, Runnable runnable) {
        if (EventRunner.getMainEventRunner().isCurrentRunnerThread()) {
            runnable.run();
        } else {
            if (uiHandler == null) {
                synchronized (ThreadUtil.class) {
                    if (uiHandler == null) {
                        uiHandler = new EventHandler(EventRunner.getMainEventRunner());
                    }
                }
            }
            uiHandler.postTask(runnable);
            addUiRunnable(token, runnable);
        }
    }


    /**
     * 提供线程管理的子线程调用方法
     */
    public static void runOnSubThread(Object token, Runnable runnable) {
        if (EventRunner.getMainEventRunner().isCurrentRunnerThread()) {
            if (mThreadPool == null) {
                synchronized (ThreadUtil.class) {
                    if (mThreadPool == null) {
                        mThreadPool = Executors.newCachedThreadPool();
                    }
                }
            }
            Future<?> future = mThreadPool.submit(runnable);
            addSubRunnable(token, runnable, future);
        } else {
            runnable.run();
        }
    }

    ...
}

更多实现可以上github下载

Toast封装:

public class Toast {

    public static void show(Context context, String message) {
        obtainToastDialog(context, message).show();
    }

    private static ToastDialog obtainToastDialog(Context context, String text) {
        Text textComponent = new Text(context);
        textComponent.setText(text);
        int padding = ResourceUtils.vpToPx(context, 10);
        //设置间距为10vp
        textComponent.setPadding(padding, padding, padding, padding);
        textComponent.setTextColor(Color.WHITE);
        textComponent.setTextAlignment(TextAlignment.CENTER);
        textComponent.setTextSize(ResourceUtils.vpToPx(context, 14));
        ShapeElement shapeElement = new ShapeElement();
        shapeElement.setShape(ShapeElement.RECTANGLE);
        shapeElement.setCornerRadius(ResourceUtils.vpToPx(context, 5));
        //设置背景半透明
        shapeElement.setRgbColor(RgbColor.fromArgbInt(Color.argb(127, 0, 0, 0)));
        textComponent.setBackground(shapeElement);
        //设置文字允许多行
        textComponent.setMultipleLine(true);
        textComponent.setMinWidth(ResourceUtils.vpToPx(context, 120));

        DirectionalLayout.LayoutConfig layoutConfig = new DirectionalLayout.LayoutConfig();
        layoutConfig.width = ComponentContainer.LayoutConfig.MATCH_CONTENT;
        layoutConfig.height = ComponentContainer.LayoutConfig.MATCH_CONTENT;
        layoutConfig.alignment = LayoutAlignment.CENTER;
        textComponent.setLayoutConfig(layoutConfig);

        ToastDialog toastDialog =  new ToastDialog(context)
                .setDuration(500)
                .setComponent(textComponent)
                .setAlignment(LayoutAlignment.CENTER);
        //设置弹框背景透明
        toastDialog.setTransparent(true);
        return toastDialog;
    }
}

BaseAbility关键实现:

public abstract class BaseAbility<T extends BasePresenter> extends Ability implements IBaseView {

    private T presenter;

    @Override
    protected final void onStart(Intent intent) {
        super.onStart(intent);
        Logger.d(getAbilityName() + " onStart");
        getPresenter().onCreate(this);
        int layout = getLayout();
        if (layout > 0) {
            setUIContent(layout);
        }
        initView(intent);
    }

    // Ability销毁,对应Android Activity的onDestroy
    @Override
    protected void onStop() {
        super.onStop();
        Logger.d(getAbilityName() + " onStop");
        ThreadUtil.removeRunnable(this);
        getPresenter().onDestroy();
    }

    @Override
    public void finish() {
        terminateAbility();
    }

    protected T getPresenter() {
        if (presenter == null) {
            try {
                Type type = getClass().getGenericSuperclass();
                if (type instanceof ParameterizedType) {
                    Type[] generics = ((ParameterizedType) type).getActualTypeArguments();
                    presenter = ((Class<T>) generics[0]).newInstance();
                } else {
                    throw new RuntimeException("BaseAbility子类必须指定泛型类型");
                }
            } catch (Exception e) {
                throw new RuntimeException(e);
            }
        }
        return presenter;
    }

    @Override
    public void showToast(final String message, final Object... args) {
        ThreadUtil.runOnUiThread(this, () -> {
            String msg;
            if (args == null || args.length == 0) {
                msg = message;
            } else {
                msg = String.format(message, args);
            }
            Toast.show(getCurrentContext(), msg);
        });
    }

    @Override
    public <V extends Component> V findViewById(int id) {
        return (V) findComponentById(id);
    }

    protected abstract int getLayout();
    protected abstract void initView(Intent intent);
}

 

上一篇:谈谈Android中的消息提示那些坑


下一篇:安卓开发之广播机制