Android Studio一个简单横向跑马灯的实现

时间:2022-08-25 13:02:20

记录一个Android中简单实现跑马灯功能的方法:仅仅实现了单行跑马灯的功能,对于速度的调整 ,没有实现。记录一下以便日后查看。


首先在MainActivity下新建一个名为MarqueeTextView的.java 文件

MarqueeTextView.java代码如下:

package com.example.chenhy.pmdtest;

import android.content.Context;
import android.graphics.Rect;
import android.text.TextUtils;
import android.util.AttributeSet;
import android.widget.TextView;

public class MarqueeTextView extends TextView
{
private int speed = 4;

public void setSpeed(int speed) {
this.speed = speed;
}
public MarqueeTextView(Context context)
{
this(context, null);
}

public MarqueeTextView(Context context, AttributeSet attrs)
{
super(context, attrs);

setFocusable(true);
setFocusableInTouchMode(true);

setSingleLine();
setEllipsize(TextUtils.TruncateAt.MARQUEE);
setMarqueeRepeatLimit(-1);
}

public MarqueeTextView(Context context, AttributeSet attrs, int defStyle)
{
super(context, attrs, defStyle);

setFocusable(true);
setFocusableInTouchMode(true);

setSingleLine();
setEllipsize(TextUtils.TruncateAt.MARQUEE);
setMarqueeRepeatLimit(-1);
}


@Override
protected void onFocusChanged(boolean focused, int direction, Rect previouslyFocusedRect)
{
if (focused)
{
super.onFocusChanged(focused, direction, previouslyFocusedRect);
}
}

@Override
public void onWindowFocusChanged(boolean focused)
{
if (focused)
{
super.onWindowFocusChanged(focused);
}
}

@Override
public boolean isFocused()
{
return true;
}
}


布局文件
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/activity_main"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
tools:context="com.example.chenhy.pmdtest.MainActivity">

<com.example.chenhy.pmdtest.MarqueeTextView
android:id="@+id/pmd"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:textSize="30sp"
/>


</LinearLayout>


最后是mainactivity中的代码
package com.example.chenhy.pmdtest;

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.Menu;

public class MainActivity extends AppCompatActivity {

MarqueeTextView PMD ;

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);

PMD = (MarqueeTextView)findViewById(R.id.pmd);
PMD.setText("塞纳河畔 左岸的咖啡 我手一杯 品尝你的美 留下唇印的嘴 花店玫瑰 名字写错谁 告白气球 风吹到对街 微笑在天上飞");
}


}

最后,上一张效果图
Android Studio一个简单横向跑马灯的实现
Android Studio一个简单横向跑马灯的实现