問題
需要跑馬燈的TextView和其他的View在同一個ViewGroup下, 有時候需要改動這個ViewGroup下其他View的LayoutParam,這個修改過程可能導致TextView暫時性失去焦點,表現爲跑馬燈效果會被重置,很難看。
解決方法
一般是採取隔離政策,把其他需要改動LayoutParam的View和跑馬燈的TextView隔離開,用一個FrameLayout隔離一下。
<FrameLayout android:layout_width="0dp"
android:layout_height="wrap_content"
android:id="@+id/song_name_container"
app:layout_constraintEnd_toStartOf="@+id/more_action"
app:layout_constraintBottom_toBottomOf="@+id/more_action"
app:layout_constraintStart_toStartOf="parent" android:layout_marginStart="40dp"
android:layout_marginEnd="32dp">
<com.example.piaproboxanimation.Activity.FocusedTextView
android:text="你就不要想起我 - 陳奕迅簡弘亦周杰倫合唱 "
android:ellipsize="marquee"
android:marqueeRepeatLimit="marquee_forever"
android:focusable="true"
android:focusableInTouchMode="true"
android:singleLine="true"
android:textSize="22sp"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:textColor="@color/colorWhite"
android:id="@+id/song_name"
/>
</FrameLayout>
其中FocusedTextView繼承自TextView,目的是重寫isFocused()方法欺騙系統讓FocusedTextView獲得焦點,代碼如下:
public class FocusedTextView extends android.support.v7.widget.AppCompatTextView {
public FocusedTextView(Context context) {
super(context);
}
public FocusedTextView(Context context, AttributeSet attrs) {
super(context, attrs);
}
public FocusedTextView(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
}
/**
* 欺騙系統,讓系統認爲FocusedTextView得到了焦點了
*/
@Override
public boolean isFocused() {
return true;
}
}