Android TV列表焦点保存方法:
在TV中,当左右移动焦点时,我们需要保留列表原来选中的位置,通过LisView 中的onFocusChanged()
这个方法可以进行保存光标,通过记录上一次焦点所在的View距离Y轴的偏移量,重新让listview显示到该位置(注意)
@Override
protected void onFocusChanged(boolean gainFocus, int direction, Rect previouslyFocusedRect) {
int lastSelectItem = getSelectedItemPosition();//获取上一次的位置,注意在super之前获取
super.onFocusChanged(gainFocus, direction, previouslyFocusedRect);
if (gainFocus) {//是否有焦点
View v = getChildAt(lastSelectItem - getFirstVisiblePosition());//获取当前显示界面中上一次有焦点的view
int top = (v == null) ? 0 : v.getTop();//获取偏移量
setSelectionFromTop(lastSelectItem, top);//让listview定位到指定位置
}
}
完整代码如下
public class MyListView extends ListView {
public MyListView(Context context) {
super(context);
}
public MyListView(Context context, AttributeSet attrs) {
super(context, attrs);
}
public MyListView(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
}
@Override
protected void onFocusChanged(boolean gainFocus, int direction, Rect previouslyFocusedRect) {
int lastSelectItem = getSelectedItemPosition();
super.onFocusChanged(gainFocus, direction, previouslyFocusedRect);
if (gainFocus) {
View v = getChildAt(lastSelectItem - getFirstVisiblePosition());
int top = (v == null) ? 0 : v.getTop();
setSelectionFromTop(lastSelectItem, top);
}
}
}
xml代码如下:
<com.tv.demo.view.MyListView
android:id="@+id/listView"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:listSelector="@drawable/selector" />
selector代码如下:
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:drawable="@color/blue" android:state_selected="true" />
<item android:drawable="@color/blue" android:state_focused="true" />
</selector>
效果图(手机效果和TV一样,就不麻烦建模拟器了):