本文实例讲述了Android开发实现自动切换文字TextSwitcher功能。分享给大家供大家参考,具体如下:
介绍:
1.TextSwitcher是ViewSwicher的一个子类,继承了ViewSwicher的所有方法
2.与ViewSwitcher的另一个子类类似,TextSwitcher也有
3.ImageSwitcher不同的是:TextSwitcher的ViewFactory方法的 makeVieW()
必须放回一个TextXiew组件.
具体效果:
放射思维:
如果将其和轮播图(http://www.tuohang.net/article/245944.html)结合 就可以实现带文字效果的轮播图。
这里先给出布局文件:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
|
<? xml version = "1.0" encoding = "utf-8" ?> < RelativeLayout xmlns:android = "http://schemas.android.com/apk/res/android" android:layout_width = "match_parent" android:layout_height = "match_parent" android:gravity = "center_horizontal" > <!--定义一个ViewSwitcher并且制定了文本切换时的动画效果--> < TextSwitcher android:id = "@+id/textSwitcher" android:layout_width = "match_parent" android:layout_height = "wrap_content" android:inAnimation = "@android:anim/slide_in_left" android:outAnimation = "@android:anim/slide_out_right" android:onClick = "next" > </ TextSwitcher > </ RelativeLayout > |
关于文字定时切换的实现:
1.首先写一个next方法,再这个歌方法中调用父类的setText()
方法 实现了文字的设定
2.再主线程中开设一个性的线程用于图片的切换 注意:线程中不能直接改变View,所以要发送小修再Handler对象中改变布局内容(文字)
实现如下:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
|
public class MainActivity extends Activity { String[] string = new String[]{ "我爱高数" , "我爱概率论" , "我爱计算机网络" , "我爱操作系统" }; TextSwitcher textSwitcher; int curStr ; Handler handler = new Handler(){ @Override public void handleMessage(Message msg) { next( null ); } }; @Override protected void onCreate(Bundle savedInstanceState) { super .onCreate(savedInstanceState); setContentView(R.layout.activity_main); textSwitcher = (TextSwitcher) findViewById(R.id.textSwitcher); textSwitcher.setFactory( new ViewSwitcher.ViewFactory() { @Override public View makeView() { TextView textView = new TextView(MainActivity. this ); textView.setTextSize( 40 ); textView.setTextColor(Color.RED); return textView; } }); new Thread(){ @Override public void run() { while ( true ){ Message message = handler.obtainMessage(); message.obj = 0 ; handler.sendMessage(message); try { sleep( 1000 ); } catch (InterruptedException e) { e.printStackTrace(); } } } }.start(); } private void next(View scource){ textSwitcher.setText(string[curStr = ( curStr++ % string.length )]); } } |
希望本文所述对大家Android程序设计有所帮助。
原文链接:https://blog.csdn.net/qq_43377749/article/details/84979578