Android textView实现跑马灯效果

直接代码展示
xml文件

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    tools:context=".MainActivity">

    <TextView
        android:id="@+id/tv"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginTop="20dp"
        android:layout_gravity="center"
        android:text="跑马灯效果,点击暂停"/>
    <!-- marquee为跑马灯-->
    <!--ellipsize为超出文本后省略方式-->
    <TextView
        android:text="中方一直以高度负责任的态度和最大的诚意推动中美经贸磋商,但决不会屈服于美方的极限施压,在原则问题上不会妥协。"
        android:id="@+id/tv_marquee"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginTop="20dp"
        android:textSize="17sp"
        android:textColor="#000000"
        android:singleLine="true"
        android:ellipsize="marquee"

        android:focusable="true"
        android:focusableInTouchMode="true" />  <!--  focusable 是否获得焦点,跑马灯要求为true
                                                          focusable 为在触摸时是否获得焦点,跑马灯
                                                          要求为true-->
    <Button
        android:id="@+id/pause"
        android:text="pause"
        android:layout_width="match_parent"
        android:layout_height="wrap_content" />

</LinearLayout>

MainActivity的代码

public class MainActivity extends AppCompatActivity implements View.OnClickListener {
    private TextView tv_marquee; // 声明一个文本视图对象
    private Button pause;
    private boolean isPaused = false; // 跑马灯文字是否暂停滚动
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        // 从布局文件中获取名叫tv_marquee的文本视图
        tv_marquee = (TextView) findViewById(R.id.tv_marquee);

        pause = (Button) findViewById(R.id.pause);
        pause.setOnClickListener(this);



    }

    @Override
    public void onClick(View view) {
        if (view.getId() == R.id.pause) { // 点击了按钮
            isPaused = !isPaused;
            if (isPaused) {
                tv_marquee.setFocusable(false); // 不允许获得焦点
                tv_marquee.setFocusableInTouchMode(false); // 不允许在触摸时获得焦点
            } else {
                tv_marquee.setFocusable(true); // 允许获得焦点
                tv_marquee.setFocusableInTouchMode(true); // 允许在触摸时获得焦点
                tv_marquee.requestFocus(); // 强制获得焦点,让跑马灯滚起来
            }

        }
    }
}

效果图
DEMO

  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值