像360懸浮窗那樣,用WindowManager實(shí)現(xiàn)炫酷的懸浮迷你音樂盒(下)

懸浮窗

在上一篇文章像360懸浮窗那樣,用WindowManager實(shí)現(xiàn)炫酷的懸浮迷你音樂盒(上)中我粗粗的向大家介紹了WindowManager和WindowManager.LayoutParams,講的都是理論知識(shí),現(xiàn)在我們就要?jiǎng)悠鹗謥?,著手開發(fā)炫酷的懸浮迷你音樂盒了。先上效果圖:

怎么樣,是否打動(dòng)你繼續(xù)往下看呢?

如果對WindowManager沒有接觸過得小伙伴,建議先看我的上一篇文章,因?yàn)?,兩篇連著一起看才好看哦。其實(shí)實(shí)現(xiàn)這么一個(gè)懸浮迷你音樂盒的功能也并不難,首先需要兩個(gè)布局,一個(gè)就是像效果圖中展示的可以四處拖動(dòng)的View的布局我們暫且稱它為floatView,它的實(shí)現(xiàn)很簡單其實(shí)就是我之前講過的用RotateDrawable實(shí)現(xiàn)網(wǎng)易云音樂唱片機(jī)效果的迷你版。另一個(gè)就是點(diǎn)擊floatView后跳出的歌曲控制菜單的布局,我們可以叫它playerView。

floatView.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_height="match_parent"
    android:layout_width="match_parent" >

    <RelativeLayout
        android:background="@drawable/shape_background_light"
        android:layout_centerInParent="true"
        android:layout_height="52dp"
        android:layout_width="52dp" >

        <ImageView
            android:id="@+id/mini_cd"
            android:src="@drawable/rotate_cd"
            android:layout_width="match_parent"
            android:layout_height="match_parent" />

        <ImageView
            android:id="@+id/mini_hander"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:src="@drawable/rotate_hander" />
    </RelativeLayout>
</RelativeLayout>
playerView.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_height="match_parent"
    android:layout_width="match_parent" >

    <LinearLayout
        android:background="@drawable/shape_background_dark"
        android:layout_centerInParent="true"
        android:layout_height="wrap_content"
        android:layout_width="wrap_content"
        android:orientation="vertical"
        android:paddingRight="12dp"
        android:paddingLeft="12dp"
        android:paddingTop="8dp"
        android:gravity="center" >

        <TextView
            android:layout_height="wrap_content"
            android:id="@+id/player_displayname"
            android:focusableInTouchMode="true"
            android:ellipsize="marquee"
            android:layout_width="180dp"
            android:textColor="#11CD6E"
            android:singleLine="true"
            android:focusable="true"
            tools:text="淺唱 - 許嵩"
            android:gravity="center"
            android:textSize="18sp"
            android:text="N/A" />

        <RelativeLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content" >

            <TextView
                android:id="@+id/player_progress"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_alignParentLeft="true"
                android:layout_marginLeft="8dp"
                android:layout_marginTop="3dp"
                tools:text="04:15"
                android:text="--:--"
                android:textColor="#11CD6E"
                android:textSize="8sp" />

            <TextView
                android:id="@+id/player_duration"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_marginRight="8dp"
                android:layout_alignParentRight="true"
                android:textColor="#11CD6E"
                android:layout_marginTop="3dp"
                android:text="--:--"
                tools:text="12:45"
                android:textSize="8sp" />
        </RelativeLayout>

        <SeekBar
            android:id="@+id/player_seek"
            tools:progress="50"
            android:progress="0"
            android:max="100"
            tools:secondaryProgress="90"
            android:paddingBottom="3dp"
            android:progressDrawable="@drawable/layer_seekbar"
            android:thumb="@drawable/shape_thumb"
            android:layout_height="wrap_content"
            android:layout_width="match_parent"
            android:layout_weight="1"
            android:minHeight="2dp"
            android:maxHeight="2dp" />

        <LinearLayout
            android:layout_height="wrap_content"
            android:layout_width="wrap_content"
            android:gravity="center_vertical"
            android:orientation="horizontal"
            android:padding="6dp" >

            <ImageButton
                android:background="@null"
                android:layout_width="36dp"
                android:layout_height="36dp"
                android:id="@+id/player_previous"
                android:src="@mipmap/landscape_player_btn_pre_press" />

            <ImageButton
                android:background="@null"
                android:layout_width="48dp"
                android:layout_height="48dp"
                android:id="@+id/player_play"
                android:layout_marginLeft="18dp"
                android:layout_marginRight="18dp"
                android:src="@mipmap/landscape_player_btn_play_press" />

            <ImageButton
                android:background="@null"
                android:layout_width="36dp"
                android:layout_height="36dp"
                android:id="@+id/player_next"
                android:src="@mipmap/landscape_player_btn_next_press" />
        </LinearLayout>
    </LinearLayout>
</RelativeLayout>

布局寫好,接著就是寫一個(gè)類來控制這兩個(gè)View之間的轉(zhuǎn)換以及一些屬性的設(shè)置,代碼確實(shí)有點(diǎn),全貼出來的話,相信不少人都會(huì)看厭、看煩,我還是選擇其中比較有代表性的代碼,再進(jìn)行一番說明,可能更有助于大家理解我寫這個(gè)Demo時(shí)思考的角度,老規(guī)矩在文章末尾我會(huì)附上源碼下載地址,有興趣的小伙伴可以下載研究。

floatView的設(shè)置
public void setFloatView(View floatView) {
    if(floatView != null) {
        this.mFloatView = floatView;
        setContentView(mFloatView);
    }
}

首先,floatView的設(shè)置非常簡單。至于setContentView(mFloatView),是因?yàn)閼腋〈澳J(rèn)首先顯示的是小窗口,所以在設(shè)置MenuView的時(shí)候,就將窗口的布局設(shè)置為floatView。

playerView的設(shè)置
public void setPlayerView(View PlayerView) {
    if(PlayerView != null) {
        BackgroundView backgroundView = new BackgroundView(getContext());
        RelativeLayout.LayoutParams layoutParams = new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.WRAP_CONTENT, RelativeLayout.LayoutParams.WRAP_CONTENT);
        layoutParams.addRule(RelativeLayout.CENTER_IN_PARENT);
        PlayerView.setOnTouchListener(new TouchIntercept());
        PlayerView.setLayoutParams(layoutParams);
        backgroundView.addView(PlayerView);
        this.mPlayerView = backgroundView;
    }
}

menuView的設(shè)置相對于floatView的設(shè)置復(fù)雜一些,大家可以看到,我為添加進(jìn)來的MenuView包裹了一層BackgroundView,而這一點(diǎn)正是從PopupWindow的源碼中借鑒而來,BackgroundView是一個(gè)自定義內(nèi)部類,繼承至RelativeLayout,并且重寫按鍵點(diǎn)擊監(jiān)聽事件和觸摸事件,主要是用于PlayerView的返回鍵關(guān)閉功能和外部點(diǎn)擊關(guān)閉功能。

內(nèi)部類BackgroundView
class BackgroundView extends RelativeLayout {

    public BackgroundView(Context context) {
        super(context);
    }

    @Override
    public boolean dispatchKeyEvent(KeyEvent event) {
        if (event.getKeyCode() == KeyEvent.KEYCODE_BACK) {
            if (getKeyDispatcherState() == null) {
                return super.dispatchKeyEvent(event);
            }

            if (event.getAction() == KeyEvent.ACTION_DOWN && event.getRepeatCount() == 0) {
                final KeyEvent.DispatcherState state = getKeyDispatcherState();
                if (state != null) {
                    state.startTracking(event, this);
                }
                return true;
            } else if (event.getAction() == KeyEvent.ACTION_UP) {
                final KeyEvent.DispatcherState state = getKeyDispatcherState();
                if (state != null && state.isTracking(event) && !event.isCanceled()) {
                    closeMenu();
                    return true;
                }
            }
            return super.dispatchKeyEvent(event);
        } else {
            return super.dispatchKeyEvent(event);
        }
    }

    @Override
    public boolean onTouchEvent(MotionEvent event) {
        switch (event.getAction()) {
            case MotionEvent.ACTION_UP:
                closeMenu();
                return true;
            case MotionEvent.ACTION_OUTSIDE:
                closeMenu();
                return true;
        }
        return super.onTouchEvent(event);
    }
}
ContentView的初始化準(zhǔn)備
private void createContentView(View contentView) {
    this.mContentView = contentView;
    contentView.measure(View.MeasureSpec.UNSPECIFIED, View.MeasureSpec.UNSPECIFIED); // 主動(dòng)計(jì)算視圖View的寬高信息
    offsetY = getStatusBarHeight(getContext()) + contentView.getMeasuredHeight() / 2;
    offsetX = contentView.getMeasuredWidth() / 2;
    contentView.setOnTouchListener(new WindowTouchListener());
}

由于我們要實(shí)現(xiàn)的懸浮迷你音樂盒,是需要在兩個(gè)視圖之間進(jìn)行切換的,所以在每次視圖切換之前,我都會(huì)對先要加載的視圖進(jìn)行一個(gè)準(zhǔn)備,由代碼contentView.measure(View.MeasureSpec.UNSPECIFIED, View.MeasureSpec.UNSPECIFIED)可以看到,主動(dòng)計(jì)算出當(dāng)前View的寬高信息,還有就是getStatusBarHeight(getContext())計(jì)算設(shè)備狀態(tài)欄高度的方法,因?yàn)樵诖翱谝苿?dòng)的時(shí)候,默認(rèn)x、y指定的是窗口左上角的坐標(biāo),這樣就涉及到一個(gè)偏移量的問題,在排除偏移量問題后,我們的坐標(biāo)就會(huì)精確指定窗口的正中心。而且在代碼中能夠明顯看出,我對contentView設(shè)置了一個(gè)onTouch觸摸事件,主要是實(shí)現(xiàn)窗口的滑動(dòng),具體實(shí)現(xiàn)在后面會(huì)有介紹。

WindowManager.LayoutParams初始化配置
private void initLayoutParams() {
    getLayoutParams().flags = getLayoutParams().flags
        | WindowManager.LayoutParams.FLAG_WATCH_OUTSIDE_TOUCH  
        | WindowManager.LayoutParams.FLAG_NOT_TOUCH_MODAL;  
    getLayoutParams().dimAmount = 0.2f;   
    getLayoutParams().type = WindowManager.LayoutParams.TYPE_SYSTEM_ALERT;
    getLayoutParams().height = WindowManager.LayoutParams.WRAP_CONTENT;
    getLayoutParams().width = WindowManager.LayoutParams.WRAP_CONTENT;
    getLayoutParams().gravity = Gravity.LEFT | Gravity.TOP;
    getLayoutParams().format = PixelFormat.RGBA_8888;
    getLayoutParams().alpha = 1.0f;
    offsetX = 0;
    offsetY = getStatusBarHeight(getContext());
    getLayoutParams().x = (int) (mDisplayMetrics.widthPixels - offsetX);
    getLayoutParams().y = (int) (mDisplayMetrics.heightPixels * 1 / 4 - offsetY);
}

由上篇文章介紹,WindowManager.LayoutParams控制著窗口顯示的策略,因此在窗口顯示之前,我們要完成對WindowManager.LayoutParams的配置。由上面的代碼看出,窗口類型是系統(tǒng)提示窗口,也就上篇文章中說到的可以顯示在任何視圖之上的那種窗口類型,窗口的寬高是自適應(yīng)。對齊方式是左上角對齊。窗口的透明度為1.0,也就是不透明。雖然窗口并沒有設(shè)置屬性FLAG_NOT_FOCUSABLE,也就是說我們的窗口默認(rèn)是設(shè)置焦點(diǎn)的,但是由于我設(shè)置FLAG_WATCH_OUTSIDE_TOUCH屬性的緣故,窗口外的區(qū)域,還是能夠自由接收點(diǎn)擊觸摸事件的。

視圖切換
private void setContentView(View contentView) {
    if(contentView != null) {
        if(isShowing()) {
            getWindowManager().removeView(mContentView);
            createContentView(contentView);
            getWindowManager().addView(mContentView, getLayoutParams());
            updateLocation(getDisplayMetrics().widthPixels / 2, getDisplayMetrics().heightPixels / 2 ,true);
        } else {
            createContentView(contentView);
        }
    }
}

從代碼中可以看出,視圖切換用到的上篇文章中介紹到的視圖的移除和視圖的添加,是的,想要進(jìn)行視圖新的切換,首先要移除原有的視圖,并將需要顯示的視圖添加進(jìn)來。

窗口位置更新
private void updateLocation(float x, float y, boolean offset) {
    if(getContentView() != null) {
        if(offset) {
            getLayoutParams().x = (int) (x - offsetX);
            getLayoutParams().y = (int) (y - offsetY);
        } else {
            getLayoutParams().x = (int) x;
            getLayoutParams().y = (int) y;
        }
        getWindowManager().updateViewLayout(mContentView, getLayoutParams());
    }
}

視圖切換中用到了窗口的移除和窗口的添加,而在位置更新中用到的是WindowManger三個(gè)方法中的第三個(gè)方法窗口更新,通過傳入我們需要重新設(shè)置WindowManager.LayoutParams中的x、y位置坐標(biāo),然后更新窗口,就能實(shí)現(xiàn)窗口位置的更新操作。

contentView的觸摸事件
private final float DISTANCE = 15.0f;

class WindowTouchListener implements View.OnTouchListener {

    @Override
    public boolean onTouch(View view, MotionEvent event) {
        switch (event.getAction()) {
            case MotionEvent.ACTION_DOWN:
                if(!isOpen) {
                    down(event);
                }
                break;
            case MotionEvent.ACTION_MOVE:
                if(!isOpen) {
                    move(event);
                }
                break;
            case MotionEvent.ACTION_UP:
                if(!isOpen) {
                    up(event);
                }
                break;
            case MotionEvent.ACTION_OUTSIDE:
                if(isOpen) {
                    closeMenu();
                    return true;
                }
                break;
            default:
                break;
        }
        return false;
    }
}

/**
 * 按下事件處理
 * */
private void down(MotionEvent event) {
    downX = event.getRawX();
    downY = event.getRawY();
}

/**
 * 移動(dòng)事件處理
 * */
private void move(MotionEvent event) {
    updateLocation(event.getRawX(), event.getRawY(), true);
}

/**
 * 抬起事件處理
 * */
private void up(MotionEvent event) {
    float x = event.getRawX();
    float y = event.getRawY();
    if(x >= downX - DISTANCE && x <= downX + DISTANCE && y >= downY - DISTANCE && y <= downY + DISTANCE) {
        if(System.currentTimeMillis() - downTimeMillis > 1200) {
            //  長按
        } else {
            openMenu();  //點(diǎn)擊
        }
    } else {
        ValueAnimator animator = alignAnimator(x, y);
        animator.start();
    }
}

floatView的觸摸監(jiān)聽事件非常簡單,就是根據(jù)手指觸摸的坐標(biāo)位置實(shí)時(shí)刷新窗口的坐標(biāo)位置,當(dāng)up坐標(biāo)和dowm坐標(biāo)的區(qū)域在預(yù)先設(shè)置好的合理范圍內(nèi),觸摸事件超過1秒鐘則視為長按事件,小于1秒鐘則視為點(diǎn)擊事件,移除floatView,添加playerView。注意區(qū)別MotionEvent的getX、getY和getRawX、getRawY方法,getX、getY點(diǎn)擊位置在視圖內(nèi)的坐標(biāo),getRawX、getRawY則是點(diǎn)擊位置相對于整個(gè)屏幕的坐標(biāo)

打開PlayerView
public void openMenu() {
    if(isOpen) {
        return ;
    }
    getLayoutParams().height = WindowManager.LayoutParams.MATCH_PARENT;  
    getLayoutParams().width = WindowManager.LayoutParams.MATCH_PARENT; 
    oldX = getLayoutParams().x;
    oldY = getLayoutParams().y;
    setContentView(mPlayerView);
    isOpen = true;
}

打開playerView后,我設(shè)置的的窗口大小是占滿整個(gè)屏幕,這樣就能完全捕捉到BackgroundView中設(shè)置的觸摸事件,實(shí)現(xiàn)點(diǎn)擊窗口外部關(guān)閉的效果。oldX、oldY則用于記錄floatView移除前的坐標(biāo),方便在重新顯示的時(shí)候定位。

關(guān)閉PlayerView
public void closeMenu() {
    if(!isOpen) {
        return ;
    }
    isOpen = false;
    getLayoutParams().height = WindowManager.LayoutParams.WRAP_CONTENT;
    getLayoutParams().width = WindowManager.LayoutParams.WRAP_CONTENT;
    setContentView(mFloatView);
    updateLocation(oldX, oldY, false);
}

關(guān)閉PlayerView的方法也很簡單,就是重新將試圖切換為floatView,設(shè)置窗口大小為自適應(yīng)大小,并定位在之前視圖記錄的原有坐標(biāo)。

到這里炫酷的懸浮音樂盒的實(shí)現(xiàn)也就實(shí)現(xiàn)的差不多了,其實(shí)幾個(gè)在效果圖中能夠看到的樣子沒有介紹,例如:自定義SeekBar樣式的使用,懸浮窗移動(dòng)時(shí),手指離開屏幕,懸浮穿自動(dòng)依附到屏幕兩側(cè)的過渡動(dòng)畫,還有就是在3秒鐘左右懸浮窗沒有任何操作是變得透明的效果的實(shí)現(xiàn)。想要了解這些是怎么實(shí)現(xiàn)的小伙伴,可以猛戳下方鏈接下載源碼進(jìn)行研究哦!!

說明:無意間發(fā)現(xiàn)之前發(fā)布的源碼存在問題,不知道已經(jīng)下載的小伙伴有沒有發(fā)現(xiàn)。就是在我們懸浮窗(迷你狀態(tài))顯示的時(shí)候,點(diǎn)擊任意應(yīng)用的輸入框,也是不會(huì)彈出輸入法的,因?yàn)榻裹c(diǎn)讓我們的懸浮窗搶占了。哈哈,問題已經(jīng)整改,然后再加上之前邏輯上的一些錯(cuò)誤,統(tǒng)統(tǒng)也都整改。再一個(gè),為了減小demo包的大小,我音頻播放的是之前寫畢設(shè)用的后臺(tái)在線音樂,所以使用demo的時(shí)候請確保網(wǎng)絡(luò)處于連接狀態(tài)?。?br> Github地址

如果文中有表述不當(dāng)或闡述錯(cuò)誤的地方,還望正在看文章的您可以幫忙指出,有疑惑也可以在評論區(qū)提問或者私信,期待您的意見和建議,歡迎關(guān)注交流。

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容