一、基础知识
px:像素点
dp:与像素密度相关
sp:类似dp(一般用来修饰文字)
dp会在不同的设备上显示的大小差不多;
转换公式
/**
* 根据手机的分辨率从 dp 的单位 转成为 px(像素)
*/
public static int dip2px(Context context, float dpValue) {
final float scale = context.getResources().getDisplayMetrics().density;
return (int) (dpValue * scale + 0.5f);
}
/**
* 根据手机的分辨率从 px(像素) 的单位 转成为 dp
*/
public static int px2dip(Context context, float pxValue) {
final float scale = context.getResources().getDisplayMetrics().density;
return (int) (pxValue / scale + 0.5f);
}
LayoutInflater:它的作用类似于findViewById()。不同点是LayoutInflater是用来找res/layout/下的xml布局文件,并且实例化。而findViewById()是找xml布局文件下的具体widget控件(如Button、TextView等)
inflate:具体实现方法,将xml -> view
获取LayoutInflater的方法
getLayoutInflater();
getSystemService(LAYOUT_INFLATER_SERVICE);
LayoutInflater.from(context)
提取布局的属性
Theme:是窗体级别的
Style:是针对窗体元素级别的,改变指定控件或者layout的样式
可以继承,作用是抽取共同属性,如字体的大小,颜色,字体等
二、自定义控件
View的工作流程
- 构造器初始化
- 三个构造方法,统一入口
- onMeasure() 定大小
- onLayout() 定位置
- onDraw() 绘制
- 这里不要进行new对象
- invalidate() 刷新
主要形式
- 继承已有的控件来实现
- 通过继承一个布局文件实现
- 通过继承view来实现
属性
-
res -> valuse -> attrs.xml
<resources> <declare-styleable name="TestRedButton"> <attr name="backgroundColor" format="color"/> </declare-styleable> </resources>
-
自定义类中初始化
TypedArray typedArray = context.obtainStyledAttributes(attrs,R.styleable.TestRedButton); mBackgroundColor = ypedArray.getColor(R.styleable.TestRedButton_backgroundColor,Color.RED);
-
布局文件中使用
<com.dy.myapplication.TestRedButton
android:layout_width="200dp"
android:layout_height="200dp"
app:backgroundColor="@color/colorPrimary"/>
一个简单的小例子
public class TestRedButton extends View implements View.OnClickListener {
private Paint mPaint;
private Rect mRect;
private int number = 20;
private int mBackgroundColor;
public TestRedButton(Context context) {
this(context,null);
}
public TestRedButton(Context context, @Nullable AttributeSet attrs) {
this(context, attrs,0);
}
public TestRedButton(Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
init(context,attrs);
}
private void init(Context context,AttributeSet attrs) {
mPaint = new Paint();
mRect = new Rect();
this.setOnClickListener(this);
TypedArray typedArray = context.obtainStyledAttributes(attrs,R.styleable.TestRedButton);
mBackgroundColor = typedArray.getColor(R.styleable.TestRedButton_backgroundColor,Color.RED);
}
@Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
// mPaint.setColor(Color.RED);
mPaint.setColor(mBackgroundColor);
canvas.drawCircle(getWidth()/2,getHeight()/2,getWidth()/2,mPaint);
mPaint.setColor(Color.WHITE);
mPaint.setTextSize(60);
String text = String.valueOf(number);
mPaint.getTextBounds(text,0,text.length(),mRect);
int textWidth = mRect.width();
int textHeight = mRect.height();
canvas.drawText(text,getWidth()/2 - textWidth/2,getHeight()/2 + textHeight/2,mPaint);
}
@Override
public void onClick(View v) {
number --;
invalidate(); // 刷新视图
}
}