Android-自动切换文字TextSwitcher

版权声明:个人学习记录,由于能力和时间有限,如果有错误望读者纠正,谢谢! 转载请注明出处 谢谢合作 https://blog.csdn.net/qq_43377749/article/details/84979578

介绍:

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

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

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

具体效果:

放射思维:

如果将其和轮播图(https://blog.csdn.net/qq_43377749/article/details/84347089)结合 就可以实现带文字效果的轮播图。

这里先给出布局文件:

<?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 )]);
    }
}

猜你喜欢

转载自blog.csdn.net/qq_43377749/article/details/84979578