一:在java中,自定义类想要比较需要实现Comparable接口,并重写compareTo方法
二:可以使用工具类Collections.sort(haoHanArrayList);对自定义集合进行排序
三:除以2,可以使用乘以0.5f,这样不容易丢失精度
四:要让字母显示在父控件的中间,可以如下:
//1 绘制 A-Z 26个字母 for (int i = 0; i < LETTERS.length; i++) { mPaint.setColor(i == lastTouchIndex ? Color.GREEN : Color.WHITE); //获取到字母的边界矩形 Rect rect = new Rect(); mPaint.getTextBounds(LETTERS[i], 0, LETTERS[i].length(), rect); //把字母画在单元格的中间 float x = ceilWidth * 0.5f - rect.width() * 0.5f; float y = ceilHeight * 0.5f + rect.height() * 0.5f + i * ceilHeight; canvas.drawText(LETTERS[i], x, y, mPaint); }五:判断触摸到哪个字母,并且提高效率
//判断触摸到了哪个字母 float downY = event.getY(); currentTouchIndex = (int) (downY / ceilHeight); if (currentTouchIndex != lastTouchIndex) { if (currentTouchIndex >= 0 && currentTouchIndex < LETTERS.length) { lastTouchIndex = currentTouchIndex; Utils.showToast(getContext(), LETTERS[lastTouchIndex]); if (mOnLetterChangeListener != null) { mOnLetterChangeListener.onLetterChange(LETTERS[lastTouchIndex]); } } }六:理解监听回调的步骤,一般自定义view肯定会用到
public void setOnLetterChangeListener(OnLetterChangeListener mOnLetterChangeListener) { this.mOnLetterChangeListener = mOnLetterChangeListener; } PRivate OnLetterChangeListener mOnLetterChangeListener; interface OnLetterChangeListener { void onLetterChange(String letter); }七:一般可以在onSizeChanged()方法中去拿到控件的宽高,并做处理
@Override protected void onSizeChanged(int w, int h, int oldw, int oldh) { //每一个字母单元格的高度 ceilHeight = h * 1.0f / LETTERS.length; //每一个字母单元格的宽度 ceilWidth = w; }八:在触摸的时候让listView跟随滚动,可以先获取到listview滚动到的位置,然后listView.setSelection(position);
qiv.setOnLetterChangeListener(new QuickIndexerView.OnLetterChangeListener() { @Override public void onLetterChange(String letter) { //找到listview需要滚动到的位置 for (int i = 0; i < haoHanArrayList.size(); i++) { if (letter.equals(haoHanArrayList.get(i).getFirstLetter())) { listView.setSelection(i); tv_header.setText(haoHanArrayList.get(i).getFirstLetter()); break; } } }});九:listview的悬浮标题通常可以用表头布局覆盖在listview顶部,然后在OnScrollListener中去修改值
listView.setOnScrollListener(new AbsListView.OnScrollListener() { @Override public void onScrollStateChanged(AbsListView view, int scrollState) { } @Override public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) { tv_header.setText(haoHanArrayList.get(firstVisibleItem).getFirstLetter()); }});十:在listview的Adapter的getview方法中,如果有需要比较上下两个条目,可以把第一条分开来
if(position == 0) {}else{}这样不容易数组越界
十一:移除handler之前的延时操作:mHandler.removeCallbacksAndMessages(null);
新闻热点
疑难解答