自定义View(1)
来源:互联网 发布:淘宝双十一利弊 编辑:程序博客网 时间:2024/06/05 05:20
1. 自定义view属性
<resources> <declare-styleable name="MyView"> <attr name="titleText" format="string" /> <attr name="titleTextColor" format="color" /> <attr name="titleTextSize" format="dimension" /> </declare-styleable></resources>
2. 构造函数中获取属性
<span style="white-space:pre"></span>TypedArray a = context.obtainStyledAttributes(attrs, R.styleable.MyView); mTitleText = a.getString(R.styleable.MyView_titleText); mTitleTextColor = a.getColor(R.styleable.MyView_titleTextColor, Color.BLACK); mTitleTextSize = a.getDimensionPixelSize(R.styleable.MyView_titleTextSize, 16); a.recycle();
3. 重写<span style="font-family: Consolas; font-size: 10.5pt; background-color: rgb(255, 255, 255);">onMeasure</span>
<span style="font-family: Consolas; font-size: 10.5pt; background-color: rgb(255, 255, 255);"></span><pre name="code" class="java">@Override protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) { int widthMode = MeasureSpec.getMode(widthMeasureSpec); int heightMode = MeasureSpec.getMode(heightMeasureSpec); int widthSize = MeasureSpec.getSize(widthMeasureSpec); int heightSize = MeasureSpec.getSize(heightMeasureSpec); int width; int height; if (widthMode == MeasureSpec.EXACTLY) { width = widthSize; } else { mPaint.setTextSize(mTitleTextSize); mPaint.getTextBounds(mTitleText, 0, mTitleText.length(), mBound); width = getPaddingLeft() + mBound.width() + getPaddingRight(); } if (heightMode == MeasureSpec.EXACTLY) { height = heightSize; } else { mPaint.setTextSize(mTitleTextSize); mPaint.getTextBounds(mTitleText, 0, mTitleText.length(), mBound); height = getPaddingTop() + mBound.height() + getPaddingBottom(); } setMeasuredDimension(width, height); }
4 重写OnDraw
@Override protected void onDraw(Canvas canvas) { mPaint.setColor(Color.YELLOW); canvas.drawRect(0, 0, getMeasuredWidth(), getMeasuredHeight(), mPaint); mPaint.setColor(mTitleTextColor); canvas.drawText(mTitleText, getWidth() / 2 - mBound.width() / 2, getHeight() / 2 + mBound.height() / 2, mPaint); }
0 0
- 自定义View(1)
- 自定义view(1)
- 自定义View(1)
- 自定义View(1)
- 自定义View(1)
- 自定义View(1):自定义文本显示
- 自定义View(1)---Topbar
- Android自定义View(1)
- android 自定义view(1)
- 初识自定义View(1)
- android 自定义 View(1)
- Android自定义View(1)
- 自定义View(一) 初识自定义view
- Android自定义View之View详解(1)
- 自定义View(1)------------自定义属性
- 自定义view(自定义属性)
- 牛刀小试-Android自定义view(1)
- Android自定义View基础(1)
- 解决winform窗体闪烁问题
- Bluetooth Keyboard Replace
- 最近项目中用hibernate分页查询的底层方法
- 南邮 OJ 1917 松牛的故事1
- excel操作之poi-ooxml
- 自定义View(1)
- 记忆存储的生理单元
- 深刻理解Linux进程间通信(IPC)
- leetcode_Majority Element II
- NGUI 九宫格纹理拉伸
- amazeui 懒加载 搜索不到图片时,如何为图片加上默认图
- Windows10 会不会成为微软的新起点?
- debugkeystore
- 如何在WebView中点击链接使用自身打开