您好,登录后才能下订单哦!
密码登录
登录注册
点击 登录注册 即表示同意《亿速云用户服务条款》
怎么在Android中使用TextSwitcher实现自动切换文字功能?相信很多没有经验的人对此束手无策,为此本文总结了问题出现的原因和解决方法,通过这篇文章希望你能解决这个问题。
布局文件:
<?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中使用TextSwitcher实现自动切换文字功能的方法了吗?如果还想学到更多技能或想了解更多相关内容,欢迎关注亿速云行业资讯频道,感谢各位的阅读!
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。