先看下效果:
device-2018-03-07-154357.gif
做車機(jī)項(xiàng)目時腮郊,需要動態(tài)更新WIFI信息雹熬,WIFI列表增加焦點(diǎn)控制
開發(fā)中遇到兩個問題
- RecyclerView搶占了item的焦點(diǎn),導(dǎo)致不顯示紅色框框
- RecyclerView刷新數(shù)據(jù)時焦點(diǎn)丟失
(刷新前焦點(diǎn)位置比刷新后大于刷新后的數(shù)據(jù)大小,這樣系統(tǒng)就會去找layout中可以獲取的焦點(diǎn)的控件,可能不會是recyclerview榴捡,這時焦點(diǎn)就會消失掉;反之朱浴,則會在recyclerview的第一個位置)
先解決第一個問題:
第一步
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="com.yftech.myapplication.MainActivity"
android:background="#000"
android:orientation="vertical">
<android.support.v7.widget.RecyclerView
android:id="@+id/recy"
android:layout_width="match_parent"
android:layout_height="wrap_content"
##表示當(dāng)子控件不需要focus的時候吊圾,recyclerview才會去獲取focus
android:descendantFocusability="afterDescendants"
/>
<Button
android:id="@+id/button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:focusable="false"
android:focusableInTouchMode="false"
android:text="刷新數(shù)據(jù)"/>
</LinearLayout>
第二步
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/item"
##必須設(shè)置
android:focusable="true"
android:focusableInTouchMode="true"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="@drawable/list_selector">
<TextView
android:id="@+id/tv_title"
android:layout_width="match_parent"
android:layout_height="@dimen/text_item_height"
android:textColor="@android:color/white"
android:gravity="left|center_vertical"
android:textSize="@dimen/item_text_size"
android:height="65dp"
android:paddingLeft="30dp"
##指的是當(dāng)前控件是否跟隨父控件的(點(diǎn)擊、焦點(diǎn)等)狀態(tài)
android:duplicateParentState="true"
/>
</LinearLayout>
搞定第一個問題:泊馈O钇埂!
重點(diǎn)解決第二個問題
1.adapter的setHasStableIds設(shè)置成true
adapter.setHasStableIds(true);
解釋:設(shè)置item是否可以有一個id(具體意思可以百度)
2.重寫adapter的getItemId方法
@Override
public long getItemId(int position) {
return position;
}
解釋:給item生成一個id梁沧,用于定位焦點(diǎn)的
3.這兩步已經(jīng)可以保存recyclerview的焦點(diǎn)了檀何,但是使用notify系列方法仍然會出現(xiàn)focus丟失的問題,現(xiàn)在官方已經(jīng)承認(rèn)這是一個bug廷支,可以暫時使用禁用notifyDataSetChanged動畫的方法來規(guī)避:
mRecyclerView.setItemAnimator(null);
搞定