项目需求:页面顶部有通知消息,内容以跑马灯形式滚动 。页面中部有内容随时间每秒种变化一次,如果TextView不做任何处理,跑马灯TextView会每秒获得一次焦点,这样就没有跑马灯效果了,所以对TextView做如下处理:
自定义MarqueeText 继承TextView, 重写onFocusChanged、onWindowFocusChanged、isFocused方法,其中前两个方法只有在获得焦点时才调用父方法,而isFocused永远返回true,最后,让MarqueeText监听OnLayoutChangeListener.
public class MarqueeText extends android.support.v7.widget.AppCompatTextView {
public MarqueeText(Context context) {
this(context,null);
}
public MarqueeText(Context context, AttributeSet attrs) {
this(context, attrs,0);
}
public MarqueeText(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
addOnLayoutChangeListener(new OnLayoutChangeListener() {
@Override
public void onLayoutChange(View v, int left, int top, int right, int bottom, int oldLeft, int oldTop, int oldRight, int oldBottom) {
LinearLayout.LayoutParams params = (LinearLayout.LayoutParams) v.getLayoutParams();
params.width = right - left;
params.height = bottom - top;
params.weight = 0;
v.removeOnLayoutChangeListener(this);
v.setLayoutParams(params);
}
});
}
@Override
protected void onFocusChanged(boolean focused, int direction, Rect previouslyFocusedRect) {
if(focused)
super.onFocusChanged(focused, direction, previouslyFocusedRect);
}
@Override
public void onWindowFocusChanged(boolean focused) {
if(focused)
super.onWindowFocusChanged(focused);
}
@Override
public boolean isFocused() {
return true;
}
布局文件:
<com.beevle.xz.checkin_staff.view.MarqueeText
android:id="@+id/tv_marquee"
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_marginLeft="9dp"
android:layout_weight="1"
android:gravity="center_vertical"
android:textSize="@dimen/tsize_small"
android:textColor="@color/gray"
android:singleLine="true"
android:ellipsize="marquee"
android:marqueeRepeatLimit ="marquee_forever"
android:text="[有新公告]:哈哈哈哈哈或或或或或或或哈哈哈哈哈或或或或或哈哈哈哈哈或或或"/>
说明:这里不需要
android:focusable="true"
android:focusableInTouchMode="true"
android:scrollHorizontally="true"
这三个属性。
|