您的位置:首页 > 移动开发 > Android开发

Android开发实现自动切换文字TextSwitcher功能示例

2019-05-02 18:02 711 查看

本文实例讲述了Android开发实现自动切换文字TextSwitcher功能。分享给大家供大家参考,具体如下:

介绍:

1.TextSwitcher是ViewSwicher的一个子类,继承了ViewSwicher的所有方法

2.与ViewSwitcher的另一个子类类似,TextSwitcher也有

3.ImageSwitcher不同的是:TextSwitcher的ViewFactory方法的 makeVieW() 必须放回一个TextXiew组件.

具体效果:

放射思维:

如果将其和轮播图(https://www.jb51.net/article/158149.htm)结合 就可以实现带文字效果的轮播图。

这里先给出布局文件:

<?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对象中改变布局内容(文字)

实现如下:

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相关内容感兴趣的读者可查看本站专题:《Android图形与图像处理技巧总结》、《Android开发入门与进阶教程》、《Android调试技巧与常见问题解决方法汇总》、《Android基本组件用法总结》、《Android视图View技巧总结》、《Android布局layout技巧总结》及《Android控件用法总结

希望本文所述对大家Android程序设计有所帮助。

您可能感兴趣的文章:

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐