1. 程式人生 > >Android-自動切換文字TextSwitcher

Android-自動切換文字TextSwitcher

介紹:

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