您的位置:首页 > 移动开发 > Android开发

android 自定义view

2016-05-20 14:15 393 查看
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 的坐标

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线程中执行



内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: