android 自定义view

1. 获取屏幕

获取屏幕高,宽,状态栏高度,title高度

DisplayMetrics  dm = new DisplayMetrics(); 

      //取得窗口属性 

     getWindowManager().getDefaultDisplay().getMetrics(dm); 

      

      //窗口的宽度 

      int screenWidth = dm.widthPixels; 

      

      //窗口高度 

      int screenHeight = dm.heightPixels; 

// 屏幕密度

      float density = dm.density;

      int densityDip = dm.densityDpi;

     

Rect frame = new Rect();

     getWindow().getDecorView().getWindowVisibleDisplayFrame(frame);

      int statusBarHeight = frame.top;

     

      int contentTop = getWindow().findViewById(Window.ID_ANDROID_CONTENT).getTop();

    //statusBarHeight是上面所求的状态栏的高度

    int titleBarHeight = contentTop -statusBarHeight;

     textView =(TextView)findViewById(R.id.screen_message);        

      textView.setText("屏幕宽度: " + screenWidth + "\n屏幕高度: " + screenHeight + "\n 密度:" + density

                                  + "\n dip密度:" + densityDip + "\n 状态栏:" );


2. 获取view 相对于父View 的座标

mBounds = new RectF(getLeft(),getTop(),getRight(),getBottom());
 view 的width,height;
        width = mBounds.right - mBounds.left;
        height = mBounds.bottom - mBounds.top;
3. 重写onMesure

    系统不会为wrap_content 测量大小,如果是设置了明确的大小,或是match_parent 那么就不用重写onMesure 了

    

MeasureSpec的specMode,一共三种类型:

EXACTLY:一般是设置了明确的值或者是MATCH_PARENT

AT_MOST:表示子布局限制在一个最大值内,一般为WARP_CONTENT

UNSPECIFIED:表示子布局想要多大就多大,很少使用,一般用在scroll view 中。

	@Override
	protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec)
	{
		int widthMode = MeasureSpec.getMode(widthMeasureSpec);
		int widthSize = MeasureSpec.getSize(widthMeasureSpec);
		int heightMode = MeasureSpec.getMode(heightMeasureSpec);
		int heightSize = MeasureSpec.getSize(heightMeasureSpec);
		int width;
		int height ;
		if (widthMode == MeasureSpec.EXACTLY)
		{
			width = widthSize;
		} else
		{
			mPaint.setTextSize(mTitleTextSize);
			mPaint.getTextBounds(mTitle, 0, mTitle.length(), mBounds);
			float textWidth = mBounds.width();
			int desired = (int) (getPaddingLeft() + textWidth + getPaddingRight());
			width = desired;
		}

		if (heightMode == MeasureSpec.EXACTLY)
		{
			height = heightSize;
		} else
		{
			mPaint.setTextSize(mTitleTextSize);
			mPaint.getTextBounds(mTitle, 0, mTitle.length(), mBounds);
			float textHeight = mBounds.height();
			int desired = (int) (getPaddingTop() + textHeight + getPaddingBottom());
			height = desired;
		}
		setMeasuredDimension(width, height);
	}
4. onSizeChange() 重新设置高宽

5. 界面的更新

Invalidate和postInvalidate,invalidate 是在UI线程中更新,通过hanlder 更新, postInvalidate 是在非UI线程中执行



發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章