Android自定义View标识当前选中的控件
一值有在用网上朋友贴出来的代码,很方便,也能学到很多东西. 这次我也贴点比较简单使用的小东西. 不怎么形容 有图有代码 自己看真想...
主体代码
Myview代码
package com.suncco.taoxie;
import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.util.AttributeSet;
import android.util.Log;
import android.view.View;
public class MyView extends View {
private int count;
private float space, radii;
private int point_normal_color, point_seleted_color;
// 选中
private int selected = 0;
// background seleted normal
public MyView(Context context, AttributeSet attrs) {
super(context, attrs);
TypedArray a = context
.obtainStyledAttributes(attrs, R.styleable.MyView);
count = a.getInteger(R.styleable.MyView_count, 3);
space = a.getDimension(R.styleable.MyView_space, 9);
radii = a.getDimension(R.styleable.MyView_point_radii, 9);
point_normal_color = a.getColor(R.styleable.MyView_point_normal_color,
0x000000);
point_seleted_color = a.getColor(
R.styleable.MyView_point_seleted_color, 0xffff07);
int sum = attrs.getAttributeCount();
a.recycle();
}
public void setCount(int count) {
this.count = count;
invalidate();
}
public void next() {
if (selected < count - 1)
selected++;
else
selected = 0;
invalidate();
}
public void previous() {
if (selected > 0)
selected--;
else
selected = count - 1;
invalidate();
}
@Override
protected void onDraw(Canvas canvas) {
Paint paint = new Paint();
paint.setAntiAlias(true);
// 起始位置,实现整体居中
float w = canvas.getWidth() - (count * 2 * radii) - space * (count - 1);
for (int i = 0; i < count; i++) {
if (i == selected)
paint.setColor(point_seleted_color);
else
paint.setColor(point_normal_color);
canvas.drawCircle(w / 2.f + radii + i * (space + radii + radii),
radii + 1, ((int) radii + 2) / 2, paint);
}
}
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
super.onMeasure(widthMeasureSpec, heightMeasureSpec);
setMeasuredDimension(widthMeasureSpec, (int) (radii * 2) + 2);
}
public void setSelected(int selectedId) {
if (selectedId >= 0 && selectedId <= count)
this.selected = selectedId;
else if (selectedId < 0)
this.selected = 0;
else if (selectedId > count)
this.selected = count;
invalidate();
}
}
自定义View 的自定义命名空间:
以下自定义属性 count: 总数, space: 每个点的距离大小之类的等等 名字取得都比较通俗了...
命名空间也直接叫myview了...代码
这个文件xml放在 value 下的 ***_attrs.xml 比如我这里去 haowuliaoa_attrs.xml
命名空间也直接叫myview了...代码
<?xml version="1.0" encoding="utf-8"?>
<resources>
<declare-styleable name="MyView">
<attr name="count" format="integer" />
<attr name="space" format="dimension" />
<attr name="point_size" format="dimension" />
<attr name="point_seleted_color" format="color|reference" />
<attr name="point_normal_color" format="color|reference" />
<attr name="point_radii" format="dimension" />
</declare-styleable>
</resources>
一切ok
补充:移动开发 , Android ,