Android 给我写一个Kotlin版本的MarqueeTextView
时间: 2024-03-29 07:34:12 浏览: 11
好的,以下是一个简单的Kotlin版本的MarqueeTextView:
```kotlin
import android.content.Context
import android.graphics.Rect
import android.util.AttributeSet
import androidx.appcompat.widget.AppCompatTextView
class MarqueeTextView @JvmOverloads constructor(
context: Context,
attrs: AttributeSet? = null,
defStyleAttr: Int = 0
) : AppCompatTextView(context, attrs, defStyleAttr) {
private val textRect = Rect()
private var isMarqueeEnabled = true
init {
setSingleLine(true)
ellipsize = null
}
override fun onTextChanged(text: CharSequence?, start: Int, lengthBefore: Int, lengthAfter: Int) {
super.onTextChanged(text, start, lengthBefore, lengthAfter)
isMarqueeEnabled = textRect.width() > width
}
override fun isFocused(): Boolean {
return isMarqueeEnabled
}
override fun onFocusChanged(focused: Boolean, direction: Int, previouslyFocusedRect: Rect?) {
if (focused) {
super.onFocusChanged(focused, direction, previouslyFocusedRect)
}
}
override fun onWindowFocusChanged(hasWindowFocus: Boolean) {
if (hasWindowFocus) {
super.onWindowFocusChanged(hasWindowFocus)
}
}
override fun computeScroll() {
if (isMarqueeEnabled) {
super.computeScroll()
}
}
override fun onMeasure(widthMeasureSpec: Int, heightMeasureSpec: Int) {
super.onMeasure(widthMeasureSpec, heightMeasureSpec)
if (isMarqueeEnabled) {
paint.getTextBounds(text.toString(), 0, text.length, textRect)
setMeasuredDimension(textRect.width() + paddingLeft + paddingRight, measuredHeight)
}
}
}
```
使用时,只需在布局文件中使用`MarqueeTextView`替代`TextView`即可:
```xml
<com.example.myapplication.MarqueeTextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="This is a long text that will scroll if it's too wide for the view"
android:singleLine="true"
android:ellipsize="marquee" />
```
请注意,如果您的文本内容太短,无法触发滚动效果,请将`isMarqueeEnabled`属性设置为`true`以启用滚动。