Android檢測View的可見度

來源:互聯網
上載者:User

標籤:change   ide   自訂   lan   and   android中   height   rect   ble   

Android中我們經常會用到判斷View的可見行,當然有人會說View.VISIBLE就可以了,但是有時候這個真是滿足不了,有時候我們為了最佳化,在View滾到得不可見的時候或者由於滾到只顯示了部分內容的時候不做某些操作,View.VISIBLE這個時候是滿足不了的。

1. onWindowVisibilityChanged檢測滾到導致View可見或者不可見

比如在 ScrollView(RecyclerView和ListView等都一樣)中滾動,會對其中的view產生生命週期影響,可以參考一下:深入理解android view 生命週期 
當 ScrollView 中的view滾動導致View不可見了,會調用 onWindowVisibilityChanged 方法,注意是完全不可見才會調用 onWindowVisibilityChanged,當滾到導致View部分可見的時候也會調用onWindowVisibilityChanged方法,注意是部分可見也會調用,這樣就可以監聽滾動控制項中View的可見度。 
我們可以重寫onWindowVisibilityChanged方法:

@Override    protected void onWindowVisibilityChanged(int visibility) {        super.onWindowVisibilityChanged(visibility);        if (visibility == View.VISIBLE){            WLog.d("danxx" ,"可見");            //開始某些任務        }        else if(visibility == INVISIBLE || visibility == GONE){            WLog.d("danxx" ,"不可見");            //停止某些任務        }    }
2. getGlobalVisibleRect檢測View是部分可見或者完全可見

onWindowVisibilityChanged方法只能判斷滾動控制項中View的可見或者不可見,無法判斷是完全可見或者是部分可見。使用下面的方法就可以判斷View是不是只是部分可見:

2.1 在自訂控制項裡面檢測當前view是否被遮住顯示不全
 /**     *      * @return     */    protected boolean isCover() {        boolean cover = false;        Rect rect = new Rect();        cover = getGlobalVisibleRect(rect);        if (cover) {            if (rect.width() >= getMeasuredWidth() && rect.height() >= getMeasuredHeight()) {                return !cover;            }        }        return true;    }
2.2 檢測我們自己制定的View作為參數去判斷顯示情況
/**     * 檢測制定View是否被遮住顯示不全     * @return     */    protected boolean isCover(View view) {        boolean cover = false;        Rect rect = new Rect();        cover = view.getGlobalVisibleRect(rect);        if (cover) {            if (rect.width() >= view.getMeasuredWidth() && rect.height() >= view.getMeasuredHeight()) {                return !cover;            }        }        return true;    }

 

Android檢測View的可見度

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.