package com.wasu.cs.widget; import java.util.ArrayList; import android.content.Context; import android.graphics.Canvas; import android.graphics.Rect; import android.graphics.drawable.Drawable; import android.util.AttributeSet; import android.view.View; import android.widget.ListView; /** * 继承listview,更好的控制焦点 */ public class TabListView extends ListView { private int mHighlighted; private boolean mClearingFocus; public TabListView(Context context) { super(context); } public TabListView(Context context, AttributeSet attrs) { super(context, attrs); } public TabListView(Context context, AttributeSet attrs, int defStyle) { super(context, attrs, defStyle); } /** * Sets the highlighted item which will receive focus whenever this list * gains focus. */ public void setHighlighted(int index) { mHighlighted = index; } @Override public void addFocusables(ArrayList views, int direction, int focusableMode) { int selectedIndex = mHighlighted - getFirstVisiblePosition(); if (!hasFocus() && selectedIndex >= 0 && selectedIndex < getChildCount() && direction == FOCUS_LEFT) { // This will force focus on the highlighted item. //setSelection(mHighlighted); smoothScrollToPosition(mHighlighted); getChildAt(selectedIndex).addFocusables(views, direction, focusableMode); } else { super.addFocusables(views, direction, focusableMode); } /*//滚动tabs if (direction == FOCUS_DOWN) { int currentPosition = mHighlighted + 1; if (currentPosition == getLastVisiblePosition()) { scrollBy(0, getChildAt(currentPosition).getHeight() + getDividerHeight()); } } else if (direction == FOCUS_UP) { int currentPosition = mHighlighted - 1; if (currentPosition == getFirstVisiblePosition()) { scrollBy(0, -(getChildAt(currentPosition).getHeight() + getDividerHeight())); } }*/ } @Override public void clearFocus() { mClearingFocus = true; super.clearFocus(); mClearingFocus = false; } /** * Whenever the geometry of the list changes, focus gets cleared. This is * problematic when the list gets expanded. Instead of letting the focus go * away, it simply gets reset slightly later. */ @Override public void clearChildFocus(View child) { if (mClearingFocus) { super.clearChildFocus(child); } else { post(new Runnable() { public void run() { smoothScrollToPosition(mHighlighted); } }); } } /** * Draws an extra divider at the top and bottom of the list. */ @Override protected void dispatchDraw(Canvas canvas) { super.dispatchDraw(canvas); Drawable divider = getDivider(); if (divider == null) { return; } Rect bounds = new Rect(); bounds.left = getPaddingLeft(); bounds.right = getRight() - getLeft() - getPaddingRight(); // Top. bounds.top = getPaddingTop(); bounds.bottom = getPaddingTop() + getDividerHeight(); divider.setBounds(bounds); divider.draw(canvas); // Bottom. bounds.top = getBottom() - getTop() - getPaddingBottom() - getDividerHeight(); bounds.bottom = getBottom() - getTop() - getPaddingBottom(); divider.setBounds(bounds); divider.draw(canvas); } }