TextSwitcher可实现仿京东通告效果
核心代码
private TextSwitcher textSwitcher_tag;
private TextSwitcher textSwitcher_title;
String[] tags = new String[]{"最新", "最火爆", "HOT", "new"};
String[] titles = new String[]{"瑞士维氏军刀 新品满200-50", "家居家装焕新季,讲199减100!", "带上相机去春游,尼康低至477", "价格惊呆!电信千兆光纤上市"};
private int curStr=0;
public static final int NEWS_MESSAGE_TEXTVIEW=100;
private Handler handler=new Handler(){
@Override
public void handleMessage(Message msg) {
super.handleMessage(msg);
switch (msg.what){
case NEWS_MESSAGE_TEXTVIEW:
curStr++;
if (curStr == tags.length) {
curStr = 0;
}
textSwitcher_tag.setText(tags[curStr]);
textSwitcher_title.setText(titles[curStr]);
break;
default:
break;
}
}
};
textSwitcher_tag= (TextSwitcher) findViewById(R.id.textSwitcher_tag);
textSwitcher_title= (TextSwitcher) findViewById(R.id.textSwitcher_title);
textSwitcher_title.setFactory(new ViewSwitcher.ViewFactory() {
@Override
public View makeView() {
final TextView tv = new TextView(MainActivity.this);
tv.setTextColor(Color.BLACK);
FrameLayout.LayoutParams params = new FrameLayout.LayoutParams(
ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT);
params.gravity = Gravity.CENTER_VERTICAL;
tv.setLayoutParams(params);
return tv;
}
});
textSwitcher_tag.setFactory(new ViewSwitcher.ViewFactory() {
@Override
public View makeView() {
final TextView tv = new TextView(MainActivity.this);
tv.setTextColor(Color.RED);
FrameLayout.LayoutParams params = new FrameLayout.LayoutParams(
ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT);
params.gravity = Gravity.CENTER_VERTICAL;
tv.setLayoutParams(params);
return tv;
}
});
textSwitcher_tag.setText(tags[0]);
textSwitcher_title.setText(titles[0]);
new Thread(){
@Override
public void run() {
if(tags.length==titles.length){
while (curStr<tags.length){
synchronized (this) {
SystemClock.sleep(4000);//每隔4秒滚动一次
handler.sendEmptyMessage(NEWS_MESSAGE_TEXTVIEW);
}
}
}
}
}.start();
textSwitcher_title.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
switch (curStr%titles.length){
case 0:
Toast.makeText(MainActivity.this,titles[0],Toast.LENGTH_SHORT).show();
break;
case 1:
Toast.makeText(MainActivity.this,titles[1],Toast.LENGTH_SHORT).show();
break;
case 2:
Toast.makeText(MainActivity.this,titles[2],Toast.LENGTH_SHORT).show();
break;
case 3:
Toast.makeText(MainActivity.this,titles[3],Toast.LENGTH_SHORT).show();
break;
default:
break;
}
}
});