Android TV 開發-listview(GridView)使用鍵盤獲取焦點時,選中上次失去焦點時的item,而不是就近的item
阿新 • • 發佈:2018-12-21
在電視上開發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);
}
}
}