387
技術社區[雲棲]
Android使listview(GridView) 獲取焦點時,選中上次失去焦點時的item,而不是就近的item
在電視上開發android應用時,經常要做有二級菜單的應用,例如:
但當我們按左鍵的時候,左邊listview的最近的item會被選中,即如下效果:
但是在電視上開發應用的時候,我們希望是上一次被選中的item重新被選中,即希望是“日期和時間”被重新選中。
為了實現這個效果,我之前上網查過很多博客都沒找到答案,也用過多個投機取巧的方法,這一次我通過查看源代碼,發現造成這個問題的原因是ListView的onFocusChanged方法會尋找最近的item,然後選中他,於是解決這個問題的根治辦法,就是重寫ListView的onFocusChanged方法,但不需寫太多代碼,該ListView獲取焦點時會選中 上次失去焦點時選中的item。下麵是該ListView的源代碼,很簡短,不多解釋了。
public class MemListView extends ListView { public MemListView(Context context) { super(context); } public MemListView(Context context, AttributeSet attrs) { super(context, attrs); } public MemListView(Context context, AttributeSet attrs, int defStyle) { super(context, attrs, defStyle); } @Override protected void onFocusChanged(boolean gainFocus, int direction, Rect previouslyFocusedRect) { int lastSelectItem = getSelectedItemPosition(); super.onFocusChanged(gainFocus, direction, previouslyFocusedRect); if (gainFocus) { setSelection(lastSelectItem); } } }
最後更新:2017-04-03 12:54:03