Android文字上下滚动
一、效果图
二、原理说明
设置两个textview,然后每一次滚动出现一个textview
三、关键代码
添加数据
private void init() {
mTextview = (AutoTextView) findViewById(R.id.textview);
titleList = new ArrayList<>();
titleList.add("2.4版本更新");
titleList.add("哈哈哈哈哈哈");
titleList.add("水水水水水水水水水水");
mTextview.setTextList(titleList);
mTextview.setText(25, 5, Color.RED);//设置属性
mTextview.setTextStillTime(3000);//设置停留时长间隔
mTextview.setAnimTime(300);//设置进入和退出的时间间隔
mTextview.setOnItemClickListener(new AutoTextView.OnItemClickListener() {
@Override
public void onItemClick(int position) {
Toast.makeText(MainActivity.this, "点击了 : " + titleList.get(position), Toast.LENGTH_SHORT).show();
}
});
}
滚动的时间间隔
public void setTextStillTime(final long time){
handler =new Handler() {
@Override
public void handleMessage(Message msg) {
switch (msg.what) {
case FLAG_START_AUTO_SCROLL:
if (textList.size() > 0) {
currentId++;
setText(textList.get(currentId % textList.size()));
}
handler.sendEmptyMessageDelayed(FLAG_START_AUTO_SCROLL,time);
break;
case FLAG_STOP_AUTO_SCROLL:
handler.removeMessages(FLAG_START_AUTO_SCROLL);
break;
}
}
};
}
设置数据源
public void setTextList(ArrayList<String> titles) {
textList.clear();
textList.addAll(titles);
currentId = -1;
}
滚动的状态设置
/**
* 开始滚动
*/
public void startAutoScroll() {
handler.sendEmptyMessage(FLAG_START_AUTO_SCROLL);
}
/**
* 停止滚动
*/
public void stopAutoScroll() {
handler.sendEmptyMessage(FLAG_STOP_AUTO_SCROLL);
}
布局代码
主布局代码
<?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"
tools:context=".MainActivity">
<com.example.myapplication.AutoTextView
android:id="@+id/textview"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
</LinearLayout>
子布局代码
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="horizontal" android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
android:id="@+id/tv_banner1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_centerVertical="true"
android:ellipsize="end"
android:singleLine="true"
android:textColor="#000"
android:textSize="12sp" />
<TextView
android:id="@+id/tv_banner2"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_centerVertical="true"
android:ellipsize="end"
android:singleLine="true"
android:textColor="#f00"
android:textSize="12sp" />
</RelativeLayout >
优化:设置监听世间
/**
* 设置点击事件监听
* @param itemClickListener
*/
public void setOnItemClickListener(OnItemClickListener itemClickListener) {
this.itemClickListener = itemClickListener;
}
/**
* 轮播文本点击监听器
*/
public interface OnItemClickListener {
/**
* 点击回调
* @param position 当前点击ID
*/
void onItemClick(int position);
}
浙公网安备 33010602011771号