package day.com.day01_viewall;
import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Rect;
import android.util.AttributeSet;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;
import java.util.ArrayList;
import static android.R.attr.width;
import static android.content.ContentValues.TAG;
/**
* autour: 周旋
* date: 2017/9/28 15:06
* update: 2017/9/28
*/
public class MyTexxtView extends View{
/**
* 需要绘制的文字
*/
private String mText;
/**
* 文本的颜色
*/
private int mTextColor;
/**
* 文本的大小
*/
private float mTextSize;
private ArrayList
mTextList;
/**
* 绘制时控制文本绘制的范围
*/
private Rect mBound;
private Paint mPaint;
public MyTexxtView(Context context) {
this(context, null);
}
public MyTexxtView(Context context, AttributeSet attrs) {
this(context, attrs, 0);
}
public MyTexxtView(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
mTextList = new ArrayList();
//获取自定义属性的值
TypedArray a = context.getTheme().obtainStyledAttributes(attrs, R.styleable.MyTextView, defStyleAttr, 0);
mText = a.getString(R.styleable.MyTextView_mText);
mTextColor = a.getColor(R.styleable.MyTextView_mTextColor, Color.BLACK);
mTextSize = a.getDimension(R.styleable.MyTextView_mTextSize, 100);
Log.v("openxu", "文本总长度:"+mText);
mPaint = new Paint();
mPaint.setTextSize(mTextSize);
mPaint.setColor(mTextColor);
//获得绘制文本的宽和高
mBound = new Rect();
mPaint.getTextBounds(mText, 0, mText.length(), mBound);
}
//API21
// public MyTextView(Context context, AttributeSet attrs, int defStyleAttr, int defStyleRes) {
// super(context, attrs, defStyleAttr, defStyleRes);
// init();
// }
@Override
protected void onDraw(Canvas canvas) {
//绘制文字
canvas.drawText(mText,88 ,88, mPaint);
Log.i(TAG, "onDraw:=====6666 ");
}
@Override
public boolean onTouchEvent(MotionEvent event) {
switch (event.getAction()){
case MotionEvent.ACTION_MOVE:
break;
case MotionEvent.ACTION_DOWN:
//获取屏幕上点击的坐标
float x=event.getX();
float y = event.getY();
float a=(float) (Math.random()*10000);
mText=""+a;
invalidate(); //更新视图
Log.i(TAG, "onTouchEventyyy:== "+y+"onTouchEventxxx:=="+x);
//如果坐标在我们的文字区域内,则将点击的文字改颜色
if(x>width-2*textWidth){
//点击后,获取坐标代表的单词的含义
index = (int) (y/(height/27));
invalidate();//更新视图
return true;
}
break;
case MotionEvent.ACTION_UP:
//点击抬起后,回复初始位置。
Log.i(TAG, "抬起");
break;
}
//这句话不要修改
return super.onTouchEvent(event);
}
}
//xml中调用
android:layout_width="wrap_content"
android:layout_height="wrap_content"
fanyl:mTextSize="25sp"
fanyl:mTextColor="#263de9"
fanyl:mText="1508A"
/>