1.自定义View类
package XXXX.widget.view;
import android.content.Context;
import android.graphics.Rect;
import android.util.AttributeSet;
import android.view.ViewGroup;
import android.widget.LinearLayout;
import androidx.appcompat.widget.AppCompatTextView;
/**
* 对于使用marquee即滚动显示方式的,需要当前textview获得焦点才会滚动
* 判断textview是否处于focused状态是通过它本身isFocused()方法
*/
public class MarqueeTextView extends AppCompatTextView {
public MarqueeTextView(Context context) {
super(context);
}
public MarqueeTextView(Context context, AttributeSet attrs) {
super(context, attrs);
}
public MarqueeTextView(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
}
@Override
public boolean isFocused() {
return true;
}
@Override
protected void onFocusChanged(boolean focused, int direction, Rect previouslyFocusedRect) {
if(focused) {
super.onFocusChanged(true, direction, previouslyFocusedRect);
}
}
@Override
public void onWindowFocusChanged(boolean focused) {
if(focused) {
super.onWindowFocusChanged(true);
}
}
@Override
protected void onSizeChanged(int w, int h, int oldw, int oldh) {
super.onSizeChanged(w, h, oldw, oldh);
ViewGroup.LayoutParams params = getLayoutParams();
params.width = w;
params.height = h;
if (params instanceof LinearLayout.LayoutParams) {
((LinearLayout.LayoutParams)params).weight = 0;
}
setLayoutParams(params);
}
}
2.在布局xml中使用。
<XXXX.widget.view.MarqueeTextView
android:id="@+id/device_name"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintStart_toStartOf="parent"
android:layout_marginTop="@dimen/dp_10"
android:layout_marginStart="@dimen/dp_5"
android:maxWidth="@dimen/dp_140"
android:ellipsize="marquee"
android:focusable="true"
android:focusableInTouchMode="true"
android:marqueeRepeatLimit="marquee_forever"
android:scrollHorizontally="true"
android:singleLine="true"
android:textSize="@dimen/sp_12"
android:gravity="center"
android:text="Light sensor"
android:textColor="@color/text_color_normal"
android:padding="2dp"
/>