android dialog根據彈窗等級排序顯示

2020-10-22 11:00:47

背景:由於主介面可能彈窗很多彈窗,需求要求某個dialog必須在前面顯示,如果再消失監聽中,線性判斷,每個dialog都去判斷工作量巨大,且不易閱讀。所以做了一個彈窗排序的專案。這裡只是講解單個activity中的彈窗排序,demo中還有維護多個activity 彈窗排序,詳細看最下面github

做到工具元件化,不侵入原專案程式碼,無需繼承,使用方便。

原理:當有一個dialog新增顯示時,判斷等級是否大於,大於則顯示,否則則新增到等待佇列

private void show(int level, Dialog dialog, DialogInterface.OnDismissListener onDismissListener){
    if(dialog == null){
        return;
    }
    DialogLevelModel topDialog = getTopShowingDialog();
    DialogLevelModel inModel = new DialogLevelModel(level, dialog, activity);
    new DismissListenerBinder(inModel,this,onDismissListener).bind();
    if(topDialog ==null || level >= topDialog.level){
        realShow(inModel);
    }else {
        waitList.sortAdd(new DialogLevelModel(level, dialog, activity));
    }
}

新增集合中要根據等級排序

public boolean sortAdd(DialogLevelModel inModel){
    Log.e("DLArrayList","add---"+inModel.level);
    int lastSize = size();
    if(lastSize == 0){
        return super.add(inModel);
    }
    int index = 0;
    for (int i = size()-1; i >=0; i--){
        DialogLevelModel temp = get(i);

        if(inModel.level >= temp.level){
            index = i+1;
            break;
        }
    }
    super.add(index,inModel);
    return true;
}

顯示的時候,判斷activity是否存在,整理集合

private void realShow(DialogLevelModel dialogLevelModel){
    waitList.remove(dialogLevelModel);
    showList.add(dialogLevelModel);
    if(dialogLevelModel.activity != null && dialogLevelModel.activity.get() != null && !dialogLevelModel.activity.get().isFinishing()){
        dialogLevelModel.dialog.show();
    }else{
        destory();
    }
}

收到dialog消失監聽,整理集合,判斷最上層dialog 和等待佇列dialog等級對比

@Override
public void onDismiss(DialogLevelModel dialogLevelModel) {
    for(int i = showList.size()-1;i>=0;i--){
        if(showList.get(i).dialog == dialogLevelModel.dialog){
            showList.remove(i);
            break;
        }
    }

    boolean flag =true;
    while (flag) {
        if(waitList.size() == 0){
            break;
        }
        DialogLevelModel tempModel = waitList.get(waitList.size() -1);
        if (getTopShowingDialog() == null) {
            realShow(tempModel);
        } else if (tempModel.level >= getTopShowingDialog().level) {
            realShow(tempModel);
        } else {
            break;
        }
    }
}

呼叫:

for(int i = 0;i<15;i++){
    final int level2 = (int)(1+Math.random()*1000);
    final Dialog dialog2 = showCommonDialog("content:level-"+level2);
    Log.e("dialoglevl","level:"+level2);
    if(i ==13){
        dialogLevelManager.showDelay(level2,2000,dialog2,MainActivity.this);
        continue;
    }
    if(i ==14){
        dialogLevelManager.showDelay(level2,3000,dialog2,MainActivity.this);
        continue;
    }
    dialogLevelManager.show(level2,dialog2,MainActivity.this);
}

結果展示:

這裡只是單個activity中新增排列顯示dialog的部分重要程式碼,要想要全部程式碼,下面github

DialogLevel如果感覺有用,請star哦