Android 自訂滾動類Tab標籤,androidtab
要求
Tab 標籤可以橫向滾動,標籤可選擇,並且在選擇的時候有標線底線。
分析
可繼承HorizontalScrollView 實現,然后里面標籤ITem可可以是TextView,底線可以在Draw方法中繪製出。
實現
/** * 向容器中添加標籤view * * @param position * @param title */ private void add****(final int position, String title) { TextView tab = new TextView(getContext()); tab.setText(title); tab.setGravity(Gravity.CENTER); tab.setSingleLine(); if (position == currentPosition) { tab.setTextColor(mTabPressTextColor); } else { tab.setTextColor(mTabTextColor); } tab.setTextSize(TypedValue.COMPLEX_UNIT_PX, mTabTextSize); tab.setBackgroundResource(tabBackgroundResId); addTab(position, tab); }
protected void onDraw(Canvas canvas) { super.onDraw(canvas); /** 繪製tab標籤底線 **/ View currentTab = tabsContainer.getChildAt(currentPosition); if (currentTab != null) { float lineLeft = currentTab.getLeft(); canvas.drawRect(lineLeft - detalLeft, mViewHeight - underlineHeight, lineLeft + currentTab.getWidth() - detalRight, mViewHeight, mLinePaint)` } }
/** * 類比動畫滾動底線 * * @param fromPosition * @param toPosition */ private void *****(int fromPosition, int toPosition) { TextView lastTab = (TextView) tabsContainer.getChildAt(fromPosition); lastTab.setTextColor(mTabTextColor); TextView currentTab = (TextView) tabsContainer.getChildAt(toPosition); currentTab.setTextColor(mTabPressTextColor); currentPosition = toPosition; float lineLeft = currentTab.getLeft(); float lineRight = currentTab.getRight(); detalLeft = lineLeft - lastTab.getLeft(); detalRight = lineRight - lastTab.getRight(); this.post(new Runnable() { @Override public void run() { if (Math.abs(detalLeft) > minDetal || Math.abs(detalRight) > minDetal) { if (Math.abs(detalLeft) > minDetal) { detalLeft = detalLeft / minDetal; } if (Math.abs(detalRight) > minDetal) { detalRight = detalRight / minDetal; } invalidate(); TabHorizontalScrollView.this.post(this); } else { invalidate(); } } }); }
/** * 標籤監聽事件 */ private OnTabItemClickListener mOnTabItemClickListener; /** * 綁定標籤切換監聽事件 * * @param listener */ public void setOnTabItemClickListener(OnTabItemClickListener listener) { mOnTabItemClickListener = listener; } /** * 標籤監聽類 * * @author jarlen * */ public interface OnTabItemClickListener { public void onClickTabItem(float value); }在Item 的TextView的OnClick的方法中調用onClickTabItem()方法,然後在Activity中實現。
如果想要此效果Demo,
代碼 = money。
請點擊臨時QQ交談,非誠勿擾!