文本切換器(TextSwitcher)的功能與用法


TextSwitcher繼承了ViewSwitcher,因此它具有與ViewSwitcher相同的特征:可以在切換View組件時使用動畫效果。與ImageSwitcher相似的是,使用TextSwitcher也需要設置一個ViewFactory。與ImageSwitcher不同的是,TextSwitcher所需的ViewFactory的makeView()方法必須返回一個TextView組件。TextSwitcher與TextView的功能有點相似,它們都可用於顯示文本內容,區別在於TextSwitcher的效果更炫,它可以指定文本切換時的動畫效果。

下面是布局文件

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="match_parent">
<!--定義一個TextSwitcher,並指定了文本切換時的動畫效果-->
<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"/>
</LinearLayout>

下面是Activity代碼

public class MainActivity extends AppCompatActivity { private TextSwitcher textSwitcher; private String[] strings = new String[]{"人生得意須盡歡", "莫使金樽空對月", "天生我材必有用", "千金散盡還復來"}; private int curStr; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); textSwitcher = findViewById(R.id.textSwitcher); textSwitcher.setFactory(() -> { TextView textView = new TextView(MainActivity.this); textView.setTextSize(40f); textView.setTextColor(Color.MAGENTA); return textView; }); //調用next方法顯示下一個字符串
        next(null); } //事件處理函數,控制顯示下一個字符串
    public void next(View source) { textSwitcher.setText(strings[curStr++ % strings.length]); } }

 

 

 

 

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM