跑马灯 自定义布局 MarqueeViewLibrary 的使用(遇到的问题)

本文介绍了在Android项目中使用MarqueeViewLibrary实现跑马灯效果时遇到的问题及其解决方案。依赖地址为implementation 'com.gongwen:marqueelibrary:1.1.3'。在尝试使用SimpleMarqueeView时遇到了ClassCastException,原因是控件被错误地转换为TextView。通过查看源码,发现需要继承MarqueeFactory并自定义布局工厂来解决类型转换错误。最终的解决办法是将控件改为MarqueeView。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

首先是依赖地址:implementation 'com.gongwen:marqueelibrary:1.1.3'

项目中遇到要写一个跑马灯的需求,由于功能很简单也不想浪费时间自己写一个,所以百度了一番发现大多数人都是使用的marqueelibrary,按照文档步骤简单的实现了下,以为就可以一次搞定。但最后在使用中发现老是报

java.lang.ClassCastException: android.widget.LinearLayout cannot be cast to android.widget.TextView

xml布局:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:orientation="horizontal">

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="@dimen/dp_35"
        android:gravity="center">
        <TextView
            android:id="@+id/content_tv"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:textColor="#ffffffff"
            android:textSize="14sp"/>
    </LinearLayout>

</LinearLayout>

控件布局:

<com.gongwen.marqueen.SimpleMarqueeView
    android:id="@+id/marqueeView"
    android:layout_width="match_parent"
    android:layout_height="@dimen/dp_35"
    android:flipInterval="2500"
    android:inAnimation="@anim/in_right"
    android:outAnimation="@anim/out_left"
    app:marqueeAnimDuration="2000" />

后面去看源码,发现SimpleMarqueeView是 extends MarqueeView<TextView, E>, 所以通过集成MarqueeFactory<T extends View, E>实现自定义布局工厂,不管是定义什么类型的view 都会报类型转换错误。

解决方式就是将控件SimpleMarqueeView改成MarqueeView。

<com.gongwen.marqueen.MarqueeView
    android:id="@+id/marqueeView"
    android:layout_width="match_parent"
    android:layout_height="@dimen/dp_35"
    android:flipInterval="2500"
    android:inAnimation="@anim/in_right"
    android:outAnimation="@anim/out_left"
    app:marqueeAnimDuration="2000" />

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值