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

软件发布|下载排行|最新软件

当前位置:首页IT学院IT技术

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

水中鱼之1999   2021-03-30 我要评论

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

介绍:

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

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

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

具体效果:

放射思维:

如果将其和轮播图(https:)结合 就可以实现带文字效果的轮播图。

这里先给出布局文件:

<?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程序设计有所帮助。

Copyright 2022 版权所有 软件发布 访问手机版

声明:所有软件和文章来自软件开发商或者作者 如有异议 请与本站联系 联系我们