话不多说先上图:
类似于这样的效果,很简单。这是一个listview,item是自定义的view,有两个特点:
- 传入长度,动态改变柱状图的长度;
- 根据长度改变色值,长度越长越红,反之越黄。
用到的知识点无非是paint在canvas上画图,这里不赘述,想了解但是不了解的童鞋可以看我上一篇日志。
传送门:http://blog.csdn.net/zhaoyingkun/article/details/44340365
在这里最想提到的一点是关于Android命名空间的使用。
是怎么想到的呢,我发现当我想往自定义的view中传入一个值如果按照常规的方式,只能使用setXXX()方法,但这个前提是此view对象已经被创建出来而且需要主动调用setXXX方法。怎么样才能在初始的时候就能像构造方法一样根据给定的值创建这个View呢?因为view的使用是在xml中使用的,不能去调用构造方法。那我们怎么办呢,这时候就需要使用命名空间了。也就是像xml中android:layout_height="20dp"这样给view赋值一样,这是二级结构的前面的android就是命名空间,只不过这个是android自己的而已。我们需要做的就是自己定义一个命名空间,我们可以拿过来用。
一、创建一个attrs.xml
<?xml version="1.0" encoding="utf-8"?>
<resources>
<declare-styleable name="BarChartView">
<attr name="text" format="string" />
<!-- bar_height表示定义的BarChartView的高度 -->
<attr name="bar_height" format="integer" />
<!-- bar_width表示定义的BarChartView的宽度 -->
<attr name="bar_width" format="integer" />
</declare-styleable>
</resources>
like this,declare-styleable,顾名思义,声明一个styleable类型,在我们下面的java代码中,我们还需要从这里边将属性取出来。
这里我们定义了两个int值:bar_height,bar_width,一个字符串值text。在下面我们马上就能用到它们。
二、布局文件中
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
<span style="color:#ff0000;">xmlns:myxmlns="http://schemas.android.com/apk/res/com.example.simple"</span>
android:layout_width="wrap_content"
android:layout_height="match_parent" >
<com.example.simple.BarChartView
android:id="@+id/cv_chart"
android:layout_width="wrap_content"
android:layout_height="20dp"
android:layout_centerVertical="true"
<span style="color:#ff0000;">myxmlns:bar_height="40"</span> >
</com.example.simple.BarChartView>
</RelativeLayout>
这是listview中作为item的view,注意红色部分,xmlns:myxmlns="http://schemas.android.com/apk/res/com.example.simple"。使用的规则为,首先定义命名空间xmlns:namespace-prefix="namespaceURI"。Android中xml中的使用是:xmlns:前缀=http://schemas.android.com/apk/res/ 应用程序包路径;然后使用的时候按格式:namespace-prefix(前缀):属性
myxmlns可以随便写,但要与下面的保持一致。这里我们就可以使用在上面的attrs.xml中定义的属性了,包括bar_height,bar_width,text等等上面你自定义的属性。
三、在代码中使用上面我们预设的属性
public BarChartView(Context context, AttributeSet attrs) {
super(context, attrs);
TypedArray a = context.obtainStyledAttributes(attrs, R.styleable.BarChartView);
chartHeight = a.getInt(R.styleable.BarChartView_bar_height, 20);
chartWidth = a.getResourceId(R.styleable.BarChartView_bar_width, 10);
a.recycle();
chartHeight = DisplayUtils.Dp2Px(context, chartHeight);
}
我们可以在自定义的view的构造方法中将我们预设的值用上面的方法得到,使用我们第一步中声明的styleable中将我们需要的属性得到。
这样我们的目的就达到了,使用了xml中预设的属性,不用再使用setXXX方法去传递view中的参数。
代码在github上,有需要的童鞋自行下载: