由於焦點衝突導致TextView的跑馬燈效果和EditText不能共存的問題
阿新 • • 發佈:2019-01-10
當我們需要TextView的跑馬燈效果時,通常會用到
android:ellipsize="marquee"
的屬性,但是該屬性只有在TextView獲取焦點時才會起效,所以一般我們會自定義TextView,繼承TextView,然後複寫isFocused方法,讓該方法返回true
public class TextView4Marquee extends android.support.v7.widget.AppCompatTextView { public TextView4Marquee(Context context) { super(context); } publicTextView4Marquee(Context context, AttributeSet attrs) { super(context, attrs); } public TextView4Marquee(Context context, AttributeSet attrs, int defStyleAttr) { super(context, attrs, defStyleAttr); } @Override public boolean isFocused() { return true; } }
但是,當佈局中包含EditText的時候,就會導致EditText獲取不到焦點而彈不出來軟鍵盤,使用以下方式可以有效避免該問題。
我們使用原生的TextView,並且不讓其獲取焦點
<TextView android:id="@+id/tv_name" android:layout_width="match_parent" android:layout_height="wrap_content" android:ellipsize="marquee" android:focusable="false" android:marqueeRepeatLimit="marquee_forever" android:singleLine="true"/>
然後在程式碼中,使用selected的屬性
tv_name.setSelected(trueselected的屬性和focused屬性不會衝突,而且selected也會使跑馬燈效果生效);