自定义初学1——扩展系统控件

来源:互联网 发布:淘宝商品详情模板代码 编辑:程序博客网 时间:2024/05/16 19:28
在Android中自定义控件时,如果Android系统中已存在对应的控件,就应该扩展功能相近的系统控件,这样既可以减少工作量,又可以避免处理复杂的绘图逻辑。代码复用是程序开发的一条重要原则,因此一定不要盲目的扩展View。

好了,先从一个扩展的TextView入手吧
public class CustomTextView extends TextView {

}
系统会提示我们建立构造函数,说一下这三个构造函数的不同。


  • public CustomTextView(Context context):通常在代码中使用,控件的所有属性都使用默认值
  • public CustomTextView(Context context, AttributeSet attrs):如果在xml布局中设置控件的属性,这些属性会存到attrs中然后传递给构造函数,这些属性值会决定控件的最终效果
  • public CustomTextView(Context context, AttributeSet attrs,int defStyle):如果需要在xml布局中为控件设置style属性,defStyle会存储style的id并将其传递给构造函数,然后控件会根据属性style的属性值设置自己的样式

我们就设置一下字体加粗吧
/**
  * 初始化画笔
  */
 private void initPaint() {
  // 实例化画笔
  mPaint=getPaint();
  // 设置字体加粗
  mPaint.setFakeBoldText(true);
 }
Paint的set方法可以设置画笔的属性,具体的可以看API的解释



然后调用onDraw(canvas)方法,否则所有绘制效果都无法展示
@Override
 protected void onDraw(Canvas canvas) {
  // TODO Auto-generated method stub
  super.onDraw(canvas);
 }
Canvas是画布的意思,Paint是画笔,通过Canvas下的各类drawXXX方法绘制各种不同的东西,然后展示在画布上
Canvas的相关drawXXX方法如下



在xml布局文件中使用自定义控件时,控件的标签必须使用控件的完整类名
activity_main.xml如下:

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent" >

    <com.example.activity.CustomTextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="这是自定义TextView"
        android:textSize="20sp" />

</RelativeLayout>

好了,现在看一下效果吧,运行效果如下:



源代码

参考:http://blog.csdn.net/aigestudio/article/details/41212583





0 0
原创粉丝点击