文字长度可变跑马灯效果

  

布局文件属性设置

<TextView

        android:id="@+id/tv_text"
        android:layout_width="90dp"
        android:layout_height="wrap_content"

        android:ellipsize="marquee"

        android:marqueeRepeatLimit="marquee_forever"

        android:focusable="true"
        android:focusableInTouchMode="true"

        android:singleLine="true" />


运行时代码

int maxWidth = getResources().getDisplayMetrics().widthPixels;

       TextView textView = (TextView) findViewById(R.id.tv_text);


public void setData(String data){

        float textLengthPx = textView.getPaint().measureText(data);
        if(maxWidth >= textLengthPx){
            data += "\t\t";
            textView.getLayoutParams().width = (int) (textLengthPx);
        }
        textView.setText(data);
        textView.requestFocus();
    }


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
实现文字加图片的跑马灯效果可以通过以下步骤: 1.创建一个包含文字和图片的布局,可以使用LinearLayout或者RelativeLayout。 2.将布局嵌套在HorizontalScrollView中,设置HorizontalScrollView的属性为滚动。 3.使用定时器或者Handler实现自动滚动,可以使用postDelayed方法实现定时滚动。 4.在滚动的过程中,需要根据内容的长度和滚动位置动态调整滚动的速度。 5.如果需要支持手动滚动,可以使用GestureDetector或者Touch事件监听实现手动滚动。 6.在滚动过程中,需要对滚动到边界的情况进行特殊处理,例如循环滚动或者停止滚动。 以下是一个简单的示例代码: ``` class MarqueeView(context: Context, attrs: AttributeSet? = null) : HorizontalScrollView(context, attrs) { private val contentView = LinearLayout(context) private var speed = 2 // 滚动速度 private var timer: Timer? = null private var isScrolling = false init { isHorizontalScrollBarEnabled = false isVerticalScrollBarEnabled = false addView(contentView) } fun start() { if (timer == null) { timer = Timer() timer?.schedule(object : TimerTask() { override fun run() { if (isScrolling) { post { scrollBy(speed, 0) if (scrollX >= contentView.width - width) { scrollTo(0, 0) } } } } }, 0, 20) } isScrolling = true } fun stop() { isScrolling = false timer?.cancel() timer = null } fun setContent(content: String, imageResId: Int) { contentView.removeAllViews() val textView = TextView(context) textView.text = content textView.textSize = 16f textView.setTextColor(Color.BLACK) textView.setPadding(10, 10, 10, 10) val imageView = ImageView(context) imageView.setImageResource(imageResId) imageView.setPadding(10, 10, 10, 10) contentView.addView(textView) contentView.addView(imageView) val layoutParams = LinearLayout.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.MATCH_PARENT) textView.layoutParams = layoutParams imageView.layoutParams = layoutParams } } ``` 使用示例: ``` val marqueeView = MarqueeView(this) marqueeView.setContent("这是一段跑马灯文字", R.drawable.ic_launcher_background) marqueeView.start() // 停止滚动 marqueeView.stop() ```

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值