1. 程式人生 > >Android --- 檢視繪製監聽

Android --- 檢視繪製監聽

// 從檢視上獲取檢視樹觀察者
ViewTreeObserver vo = mainView.getViewTreeObserver();
// 對檢視監聽即將繪製
vo.addOnPreDrawListener(new ViewTreeObserver.OnPreDrawListener() {
    @Override
    public boolean onPreDraw() {
        if(width == 0 || height ==0){
            width = mainView.getMeasuredWidth();
            height = mainView.getMeasuredHeight();
            // 取消監聽
mainView.getViewTreeObserver().removeOnPreDrawListener(this); } return true; } });

動態改變檢視的位置

// 初始化載入更多檢視的顯示位置
FrameLayout.LayoutParams lp = (FrameLayout.LayoutParams) ivLoadMore.getLayoutParams();
// 使用佈局的寬度減去載入更多檢視的寬高作為載入更多檢視的左外邊距
lp.leftMargin = width-ivLoadMore.getMeasuredWidth
(); lp.topMargin = height-ivLoadMore.getMeasuredHeight(); ivLoadMore.setLayoutParams(lp);

檢視設定觸控監聽

private View.OnTouchListener onLoadMoreTouch = new View.OnTouchListener() {
    @Override
    public boolean onTouch(View v, MotionEvent event) {
        int action = event.getAction();
        switch
(action) { case MotionEvent.ACTION_DOWN: isDraging = true; downTime = System.currentTimeMillis(); ivLoadMore.setImageResource(R.drawable.icon_load_more_press); lastPoint.set((int) event.getRawX(), (int) event.getRawY()); ivLoadMoreLayoutParam = (FrameLayout.LayoutParams) ivLoadMore.getLayoutParams(); break; case MotionEvent.ACTION_MOVE: // 獲取移動的當前點 int x = (int) event.getRawX(); int y = (int) event.getRawY(); // 計算偏移 int xDis = x - lastPoint.x; int yDis = y - lastPoint.y; // 改變左外邊距和頂部外邊距 int leftMargin = ivLoadMoreLayoutParam.leftMargin; leftMargin += xDis; if (leftMargin < 0) { leftMargin = 0; } else if (leftMargin > width - ivLoadMore.getMeasuredWidth()) { leftMargin = width - ivLoadMore.getMeasuredWidth(); } ivLoadMoreLayoutParam.leftMargin = leftMargin; int topMargin = ivLoadMoreLayoutParam.topMargin; topMargin += yDis; if (topMargin < 0) { topMargin = 0; } else if (topMargin > height - ivLoadMore.getMeasuredHeight()) { topMargin = height - ivLoadMore.getMeasuredHeight(); } ivLoadMoreLayoutParam.topMargin = topMargin; ivLoadMore.setLayoutParams(ivLoadMoreLayoutParam); ivLoadMore.invalidate(); lastPoint.set(x, y); break; case MotionEvent.ACTION_UP: resetLoadMoreView(); long currentTime = System.currentTimeMillis(); if(currentTime - downTime <= 300){ Toast.makeText(getActivity()," 載入更多 ...",Toast.LENGTH_SHORT).show(); } break; } return true; } }; ...

使用監聽

ivLoadMore.setOnTouchListener(onLoadMoreTouch);