Android自定义View仿微信LetterView效果
短信预约 -IT技能 免费直播动态提醒
废话不多说了,具体代码如下所示:
public class LetterView extends View {
private String TAG = LetterView.class.getSimpleName();
//A,B,C....Z,#
public List<String> letters;
private Paint mPaint;
private int selectPosition = -1;
private TextView mLetter;
public void setmLetter(TextView mLetter) {
this.mLetter = mLetter;
}
public LetterView(Context context) {
this(context,null);
}
public LetterView(Context context, AttributeSet attrs) {
this(context, attrs,0);
}
public LetterView(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
//生产字母
letters = new ArrayList<>();
for (int i = 65; i < 91; i++) {
letters.add(String.format(Locale.CHINA,"%c",i));
Log.e(TAG, "LetterView: "+ String.format(Locale.CHINA,"%c",i));
}
letters.add("#");//追加一个#
//初始化画笔
mPaint = new Paint();
mPaint.setAntiAlias(true);
mPaint.setColor(Color.BLUE);
mPaint.setTextSize(30);
}
@Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
int width = getMeasuredWidth();
int height = getMeasuredHeight();
//测量字的宽度
int size = letters.size();
for (int i = 0; i < size; i++) {
float textWidth = mPaint.measureText(letters.get(i));
int singleHeight = height / size;
if (selectPosition == i){//被选中的
mPaint.setColor(Color.RED);
}else{
mPaint.setColor(Color.BLUE);
}
canvas.drawText(letters.get(i),(width - textWidth)/2, singleHeight * (i + 1),mPaint);
invalidate();
}
}
@Override
public boolean onTouchEvent(MotionEvent event) {
//包装了动作,位置信息
// event.getY();//相对于View本身的坐标值
// event.getRawY();//返回的是相对于屏幕的坐标值
float y = event.getY();
Log.e(TAG, "onTouchEvent: Y:"+ y);
// Log.e(TAG, "onTouchEvent: RawY:"+event.getRawY() );
int measuredHeight = getMeasuredHeight();
int singleHeight = measuredHeight / letters.size();
int position = (int) (y / singleHeight);
Log.e(TAG, "onTouchEvent: " + position );
switch (event.getAction()) {
case MotionEvent.ACTION_MOVE:
Log.e(TAG, "onTouchEvent: ACTION_MOVE" );
case MotionEvent.ACTION_DOWN:
Log.e(TAG, "onTouchEvent: ACTION_DOWN" );
selectPosition = position;
if (mLetter != null) {
mLetter.setVisibility(View.VISIBLE);
//极限情况有可能下标越界,需要判断一下
if (position < letters.size() && position >= 0){
mLetter.setText(letters.get(position));
}
}
break;
case MotionEvent.ACTION_UP:
Log.e(TAG, "onTouchEvent: ACTION_UP" );
selectPosition = -1;
if (mLetter != null) {
mLetter.setVisibility(View.GONE);
}
break;
}
//返回true代表事件被处理了
return true;
}
}
您可能感兴趣的文章:Android编程自定义title bar(标题栏)示例Android自定义TitleView标题开发实例Android使用setCustomTitle()方法自定义对话框标题Android中自定义Window Title样式实例Android编程自定义Dialog的方法分析Android编程自定义圆角半透明Dialog的方法android自定义View滑动删除效果Android自定义TabLayout效果Android自定义手机界面状态栏实例代码Android实现自定义圆角对话框Dialog的示例代码Android动态自定义圆形进度条Android编程实现自定义title功能示例
免责声明:
① 本站未注明“稿件来源”的信息均来自网络整理。其文字、图片和音视频稿件的所属权归原作者所有。本站收集整理出于非商业性的教育和科研之目的,并不意味着本站赞同其观点或证实其内容的真实性。仅作为临时的测试数据,供内部测试之用。本站并未授权任何人以任何方式主动获取本站任何信息。
② 本站未注明“稿件来源”的临时测试数据将在测试完成后最终做删除处理。有问题或投稿请发送至: 邮箱/279061341@qq.com QQ/279061341