首先要写一个类来继承VIew 必须把所有方法都实现,否则运行的时候会运行报错。
public class SiderBar extends View {
public SiderBar(Context context) {
super(context);
}
public SiderBar(Context context, @Nullable AttributeSet attrs) {
super(context, attrs);
}
public SiderBar(Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
}
public SiderBar(Context context, @Nullable AttributeSet attrs, int defStyleAttr, int defStyleRes) {
super(context, attrs, defStyleAttr, defStyleRes);
}
new一个画笔对象,把要填充的内容以数组的形式放进去,重写onDraw方法,给画笔设置颜色,设置粗细,以及字体大小,然后获取该自定义View的宽高,并且每个字母的高度是SiderBar除以每个字母的高度。
private static Paint paint = new Paint();
private static String[] sideBar = {"热门", "A", "B", "C", "D", "E", "F", "G", "H", "I",
"J", "K", "L", "M", "N", "O", "P", "Q", "R", "S", "T", "U", "V",
"W", "X", "Y", "Z"};
@Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
paint.setColor(Color.GRAY);/*设置画笔颜色*/
paint.setTypeface(Typeface.DEFAULT_BOLD);/*设置画笔粗细*/
paint.setTextSize(32);/*设置字体大小*/
/*获取自定义View的宽高*/
int height = getHeight();
int width = getWidth();
/*设定每个字母的高度*/
int each_height = height / sideBar.length;
/*给每个字母绘制出来*/
for (int i = 0; i < sideBar.length; i++) {
float x = width / 2 - paint.measureText(sideBar[i]) / 2;
float y = (1 + i) * each_height;
canvas.drawText(sideBar[i], x, y, paint);
}
}
Siderbar自身宽度的一半减去每个字母宽度的一半就是x的偏移量,Android y轴是对半划分,所以y的偏移量是1+第几个控件*每个控件的高度求出以后,填入要画的字母,x,偏移量,画出来即可