记录一下第一次使用TextView实现跑马灯效果中遇到的问题:
关键代码:
android:layout_width="match_parent" android:layout_height="wrap_content" android:singleLine="true" android:ellipsize="marquee" //如图1.1所示,该步骤很关键,如果要实现跑马灯效果,需选择marquee android:marqueeRepeatLimit="marquee_forever" //用于选择循环的次数
图1.1
若android:ellipsize="end"效果如下:
若android:ellipsize="start"效果如下:
若android:ellipsize="middle"效果如下:
但设置了以上的代码会发现文字还是不会滚动起来,后来发现想要实现跑马灯效果文字需要获取焦点:
关键代码:
android:focusable="true"
android:focusableInTouchMode="true"
设置完了之后,运行项目发现还是没有滚动起来,原来是因为该文字还是没有真的获取焦点,解决这个问题主要有三种方法(使用的布局皆为constraintlayout):
一:
控件的完整代码如下:
<TextView android:layout_width="match_parent" android:layout_height="wrap_content" android:text="Hello World!你好世界!Hello World!你好世界!Hello World!你好世界!Hello World!你好世界!" android:singleLine="true" android:ellipsize="marquee" android:marqueeRepeatLimit="marquee_forever" android:focusable="true" android:focusableInTouchMode="true" android:clickable="true" app:layout_constraintBottom_toBottomOf="parent" app:layout_constraintLeft_toLeftOf="parent" app:layout_constraintRight_toRightOf="parent" app:layout_constraintTop_toTopOf="parent" > </TextView>
该种方法运行项目时会发现没有滚动,需要鼠标点击后才开始运行,该种方法虽然实现了跑马灯,但与现实中的需求还是有距离的。
二:
控件的完整代码如下:
<TextView android:layout_width="match_parent" android:layout_height="wrap_content" android:text="Hello World!你好世界!Hello World!你好世界!Hello World!你好世界!Hello World!你好世界!" android:singleLine="true" android:ellipsize="marquee" android:marqueeRepeatLimit="marquee_forever" android:focusable="true" android:focusableInTouchMode="true" app:layout_constraintBottom_toBottomOf="parent" app:layout_constraintLeft_toLeftOf="parent" app:layout_constraintRight_toRightOf="parent" app:layout_constraintTop_toTopOf="parent" > <requestFocus/> //添加该句获取焦点 </TextView>
该种方法运行项目时会发现文字已经开始滚动!
三:
通过java代码来实现:
MyTextView中的完整代码:
package com.example.demo; import android.content.Context; import android.util.AttributeSet; import androidx.annotation.Nullable; public class MyTextView extends androidx.appcompat.widget.AppCompatTextView { public MyTextView(Context context) { super(context); } public MyTextView(Context context, @Nullable AttributeSet attrs) { super(context, attrs); } public MyTextView(Context context, @Nullable AttributeSet attrs, int defStyleAttr) { super(context, attrs, defStyleAttr); } //重写isFocesed方法 @Override public boolean isFocused() { return true; } }
控件的完整代码:
<com.example.demo.MyTextView android:layout_width="match_parent" android:layout_height="wrap_content" android:text="Hello World!你好世界!Hello World!你好世界!Hello World!你好世界!Hello World!你好世界!" android:singleLine="true" android:ellipsize="marquee" android:marqueeRepeatLimit="marquee_forever" android:focusable="true" android:focusableInTouchMode="true" app:layout_constraintBottom_toBottomOf="parent" app:layout_constraintLeft_toLeftOf="parent" app:layout_constraintRight_toRightOf="parent" app:layout_constraintTop_toTopOf="parent" > </com.example.demo.MyTextView>
运行成功截图:
以上便是我在实现跑马灯效果时遇到的问题以及解决的方法,希望可以帮助到大家!