您好,登錄后才能下訂單哦!
如何在Android利用View模仿一個微信的LetterView效果?相信很多沒有經驗的人對此束手無策,為此本文總結了問題出現的原因和解決方法,通過這篇文章希望你能解決這個問題。
具體代碼如下所示:
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); /** * 獲取View的寬度 * 獲取View的高度 */ 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); /** * drawText() x y \_ 為基準線 */ invalidate(); } } /** * Android將觸摸事件封裝,包裝了動作,位置信息;onClick也是一種motionEvent * onClick 事件 實際上是 onTouchEvent事件 * @param event * @return */ @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利用View模仿一個微信的LetterView效果的方法了嗎?如果還想學到更多技能或想了解更多相關內容,歡迎關注億速云行業資訊頻道,感謝各位的閱讀!
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。