好久不曾写东西了.. 最近心情很舒畅,加上工作稍微轻松了些..整理下最近手里的东西.
Android 之 ViewView 是 Android 中最基本的显示类,是所有屏幕显示控件的超类. 包含了所有屏幕类型.
基于view的控件都有一个画布canvas。最终最终的展示都会通过onDraw(Canvas c)方法把画布画出来。
我们可以自定义自己的View 继承 android.view.View,重写 onDraw 方法,将自己想要的效果展示出来。
自定义 view 的使用方式
1. 直接在 activity 的布局文件中使用
<com.example.viewdemo.MyView
android:layout_width="match_parent"
android:layout_height="match_parent"
/>
2. 在 activity 中去 new
View v = new MyView(this);
this.setContentView(v);
自定义view的构造实现和构造参数
构造方法 MyView(Context contextview) context 代表 调用的Activity 对象。在Activity中调用是传参this---->> new MyView(this);
构造方法 MyView(Context context, AttributeSet attrs)
AttributeSet 的使用
1. 在res/values 文件下定义一个attrs.xml 文件
<?xml version="1.0" encoding="utf-8"?>
<resources>
<declare-styleable name="View1">
<attr name="MyColor" format="color" />
<attr name="MySize" format="dimension" />
</declare-styleable>
</resources>
2. 在构造方法中调用自定义的文件attrs.xml 中的 View1
TypedArray ta = context.obtainStyledAttributes(attrs,R.styleable.View1);
int mycolor = ta.getColor(R.styleable.View1_MyColor, 0XFFFFFFFF);
3. 直接在layout 文件中加入引用
<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"
tools:context=".MainActivity"
xmlns:app="http://schemas.android.com/apk/res/com.example.viewdemo">
首先要引入 xmlns:app="http://schemas.android.com/apk/res/com.example.viewdemo">
app 是调用自定义属性的前缀,com.example.viewdemo 项目的报名
<com.example.viewdemo.View1
android:layout_width="match_parent"
android:layout_height="match_parent"
app:MyColor="#FFFFFF"
app:MySize="989"
/>
未完.... 待续。