ListView重新獲取焦點時,讓其重新選中上次被選的item,而不是就近選擇

本文是因爲開發多了TV應用,做了很多二級菜單界面,發現需要讓一級菜單的ListView重新獲取焦點時,重新選中上次的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);
		}
	}
}


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章