UI学习(一)

相信android coder早就遇到过已有的控件满足不了工作流的情况,所以我们需要创建新的View.

创建新的View的方法与希望达到的目的有关:

(1)如果现有控件已经可以满足希望实现的功能,那么就只需要对现有控件的外观或动作经行扩展和修改即可

(2)通过组合多个控件来创建不可分割的,可重用的控件

(3)创建全新的控件

 

下面介绍第一种方法修改现有的控件,通过重写onDraw()方法来修改外观

 (1)创建一个新的扩展了TextView的MyTextView ,它包含一个 onDraw()方法,以及init()方法的构造函数

 

 

public class MyTextView extends TextView{

 

public MyTextView(Context context) {

super(context);

init();

}

public MyTextView(Context context, AttributeSet attrs, int defStyle) {

super(context, attrs, defStyle);

init();

}

public MyTextView(Context context, AttributeSet attrs) {

super(context, attrs);

init();

}

 

@Override

protected void onDraw(Canvas canvas) {

super.onDraw(canvas);

}

private void init(){

}

 

}

 

 

(2)创建资源文件

colors.xml:

<resources> <color name="notepad_paper">#AAFFFF99</color> <color name="notepad_lines">#FF0000FF</color> <color name="notepad_margin">#90FF0000</color> <color name="notepad_text">#AA0000FF</color> </resources>

dimens.xml:

 

<resources>

<dimen name="notepad_margin">30px</dimen>

</resources>

(3)通过资源文件创建外观

 

private Paint marginPaint;

private Paint linePaint;

private int paperColor;

private float margin;

 

private void init(){

Resources myResources = getResources();

//创建绘图刷

marginPaint = new Paint(Paint.ANTI_ALIAS_FLAG);

marginPaint.setColor(myResources.getColor(R.color.notepad_margin));

linePaint = new Paint(Paint.ANTI_ALIAS_FLAG);

linePaint.setColor(myResources.getColor(R.color.notepad_lines));

paperColor = myResources.getColor(R.color.notepad_paper);

margin = myResources.getDimension(R.dimen.notepad_margin);

(4)绘制页面

protected void onDraw(Canvas canvas) {

//绘制页面颜色

canvas.drawColor(paperColor);

//绘制规则的直线

canvas.drawLine(0, 0, getMeasuredHeight(), 0, linePaint);

canvas.drawLine(0, getMeasuredHeight(), getMeasuredWidth(), getMeasuredHeight(), linePaint);

//绘制边缘

canvas.drawLine(margin,0,margin,getMeasuredHeight(),marginPaint);

//移动文本,跨过边缘

canvas.save();

canvas.translate(margin, 0);

//使用TextView渲染文本

super.onDraw(canvas);

canvas.restore();

}

}

 

 

 

 

通过以上四个步骤,就完成了通过修改TextView来实现自己的View.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值