In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-02-28 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)06/02 Report--
This article mainly introduces "how to achieve letter navigation control in Android". In daily operation, I believe that many people have doubts about how to achieve letter navigation control in Android. The editor consulted all kinds of materials and sorted out simple and easy-to-use operation methods. I hope it will be helpful to answer the doubts about "how to achieve letter navigation control in Android". Next, please follow the editor to study!
The functions that can be achieved after customization are as follows:
Complete the interaction between list data and letters
Supports layout file attribute configuration
You can configure relevant properties in the layout file, such as letter color, letter font size, letter indicator color, and so on.
Custom attribute
Create an attr.xml under value, and configure the attributes that need to be customized as follows:
Then get these properties in the corresponding constructor and set the relevant properties, as follows:
Public LetterView (Context context, @ Nullable AttributeSet attrs) {super (context, attrs); / / get attributes TypedArray array = context.obtainStyledAttributes (attrs, R.styleable.LetterView); int letterTextColor = array.getColor (R.styleable.LetterView_letterTextColor, Color.RED); int letterTextBackgroundColor = array.getColor (R.styleable.LetterView_letterTextBackgroundColor, Color.WHITE); int letterIndicatorColor = array.getColor (R.styleable.LetterView_letterIndicatorColor, Color.parseColor ("# 333333")) Float letterTextSize = array.getDimension (R.styleable.LetterView_letterTextSize, 12); enableIndicator = array.getBoolean (R.styleable.LetterView_letterEnableIndicator, true); / / default settings mContext = context; mLetterPaint = new Paint (); mLetterPaint.setTextSize (letterTextSize); mLetterPaint.setColor (letterTextColor); mLetterPaint.setAntiAlias (true); mLetterIndicatorPaint = new Paint (); mLetterIndicatorPaint.setStyle (Paint.Style.FILL); mLetterIndicatorPaint.setColor (letterIndicatorColor); mLetterIndicatorPaint.setAntiAlias (true) SetBackgroundColor (letterTextBackgroundColor); array.recycle ();} Measure measurement
To accurately control the custom dimensions and coordinates, you must measure the width and height of the current custom View, and then calculate the relevant coordinates based on the measured dimensions. The specific measurement process is to inherit the View rewrite omMeasure () method to complete the measurement. The key code is as follows:
@ Overrideprotected void onMeasure (int widthMeasureSpec, int heightMeasureSpec) {super.onMeasure (widthMeasureSpec, heightMeasureSpec); / / get the dimensions of width and height int widthSize = MeasureSpec.getSize (widthMeasureSpec); int heightSize = MeasureSpec.getSize (heightMeasureSpec); / / wrap_content default width and height @ SuppressLint ("DrawAllocation") Rect mRect = new Rect (); mLetterPaint.getTextBounds ("A", 0,1, mRect); mWidth = mRect.width () + dpToPx (mContext, 12) Int mHeight = (mRect.height () + dpToPx (mContext, 5)) * letters.length; if (getLayoutParams (). Width = = ViewGroup.LayoutParams.WRAP_CONTENT & & getLayoutParams (). Height = = ViewGroup.LayoutParams.WRAP_CONTENT) {setMeasuredDimension (mWidth, mHeight);} else if (getLayoutParams (). Width = = ViewGroup.LayoutParams.WRAP_CONTENT) {setMeasuredDimension (mWidth, heightSize) } else if (getLayoutParams (). Height = = ViewGroup.LayoutParams.WRAP_CONTENT) {setMeasuredDimension (widthSize, mHeight);} mWidth = getMeasuredWidth (); int averageItemHeight = getMeasuredHeight () / 28; int mOffset = averageItemHeight / 30; / / Interface adjustment mItemHeight = averageItemHeight + mOffset;} coordinate calculation
Custom View is actually to find a suitable location on the View and draw the custom elements in an orderly manner. The most difficult part of the drawing process is how to calculate the appropriate left according to the specific requirements. As for the drawing, it is the call of API. As long as the coordinate location is calculated, there should be no problem with custom View drawing. The following illustration mainly marks the calculation of the central position coordinates drawn by the letter indicator and the starting position of the text drawing. In the process of drawing, it is necessary to ensure that the text is in the center of the indicator, as follows:
Draw
Custom View drawing operations are carried out in the onDraw () method. Here, circle drawing and text drawing are mainly used, specifically, the use of drawCircle () and drawText () methods. In order to avoid text being obscured, you need to draw a letter indicator, and then draw letters. The code is as follows:
@ Overrideprotected void onDraw (Canvas canvas) {/ / get letter width and height @ SuppressLint ("DrawAllocation") Rect rect = new Rect (); mLetterPaint.getTextBounds ("A", 0,1, rect); int letterWidth = rect.width (); int letterHeight = rect.height (); / / draw indicator if (enableIndicator) {for (int I = 1; I)
< letters.length + 1; i++) { if (mTouchIndex == i) { canvas.drawCircle(0.5f * mWidth, i * mItemHeight - 0.5f * mItemHeight, 0.5f * mItemHeight, mLetterIndicatorPaint); } } } //绘制字母 for (int i = 1; i < letters.length + 1; i++) { canvas.drawText(letters[i - 1], (mWidth - letterWidth) / 2, mItemHeight * i - 0.5f * mItemHeight + letterHeight / 2, mLetterPaint); }} 到此为止,可以说 View 的基本绘制结束了,现在使用自定义的 View 界面能够显示出来了,只是还没有添加相关的事件操作,下面将在 View 的触摸事件里实现相关逻辑。 Touch事件处理 为了判断手指当前所在位置对应的是哪一个字母,需要获取当前触摸的坐标位置来计算字母索引,重新 onTouchEvent() 方法,监听 MotionEvent.ACTION_DOWN、MotionEvent.ACTION_MOVE 来计算索引位置,监听 MotionEvent.ACTION_UP 将获得结果回调出去,具体参考如下: @Overridepublic boolean onTouchEvent(MotionEvent event) { switch (event.getAction()) { case MotionEvent.ACTION_DOWN: case MotionEvent.ACTION_MOVE: isTouch = true; int y = (int) event.getY(); Log.i("onTouchEvent","--y->"+ y +"-y mItemHeight; if-> "+ DensityUtil.px2dp (getContext (), y)); int index = y / mItemHeight; if (index! = mTouchIndex & & index)
< 28 && index >0) {mTouchIndex = index; Log.i ("onTouchEvent", "--mTouchIndex- >" + mTouchIndex + "--position- >" + mTouchIndex);} if (mOnLetterChangeListener! = null & & mTouchIndex > 0) {mOnLetterChangeListener.onLetterListener (letters [mTouchIndex-1]);} invalidate (); break Case MotionEvent.ACTION_UP: isTouch = false; if (mOnLetterChangeListener! = null & & mTouchIndex > 0) {mOnLetterChangeListener.onLetterDismissListener ();} break;} return true;}
At this point, the key parts of the customization of View are almost complete.
Data assembly
The basic idea of letter navigation is to convert a field that needs to match a letter into a corresponding letter, and then sort the data according to that field, so that the data can be matched to the same first letter through the first letter of a data field. Here, pinyin4j-2.5.0.jar is used to convert Chinese characters into pinyin, and then sort the data items according to the first letter to display the data. The Chinese characters are replaced by pinyin as follows:
/ / convert Chinese characters to Pinyin public static String getChineseToPinyin (String chinese) {StringBuilder builder = new StringBuilder (); HanyuPinyinOutputFormat format = new HanyuPinyinOutputFormat (); format.setCaseType (HanyuPinyinCaseType.UPPERCASE); format.setToneType (HanyuPinyinToneType.WITHOUT_TONE); char [] charArray = chinese.toCharArray (); for (char aCharArray: charArray) {if (Character.isSpaceChar (aCharArray)) {continue } try {String [] pinyinArr = PinyinHelper.toHanyuPinyinStringArray (aCharArray, format); if (pinyinArr! = null) {builder.append (pinyinArr [0]);} else {builder.append (aCharArray);}} catch (BadHanyuPinyinOutputFormatCombination badHanyuPinyinOutputFormatCombination) {badHanyuPinyinOutputFormatCombination.printStackTrace (); builder.append (aCharArray) }} return builder.toString ();}
As for data sorting, you can use Comparator interface.
Display effect
The display effect is as follows:
At this point, the study on "how to implement alphabetical navigation control in Android" is over. I hope to be able to solve your doubts. The collocation of theory and practice can better help you learn, go and try it! If you want to continue to learn more related knowledge, please continue to follow the website, the editor will continue to work hard to bring you more practical articles!
Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.
Views: 0
*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.