TextSwitcher,一個帶有文字切換動畫效果的加強版TextView
阿新 • • 發佈:2019-01-27
先上圖
直接上程式碼
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:orientation="vertical" android:layout_width="match_parent" android:gravity="center" android:layout_height="match_parent"> <!--inAnimation 進入時的動畫--> <!--outAnimation 退出時的動畫--> <TextSwitcher android:id="@+id/ts_test" android:layout_width="wrap_content" android:layout_height="wrap_content" android:inAnimation="@anim/anim_in" android:outAnimation="@anim/anim_out" /> <Button android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="切換下一個" android:onClick="next"/> </LinearLayout>
具體動畫程式碼 退出
<set xmlns:android="http://schemas.android.com/apk/res/android">
<translate
android:fromXDelta="0"
android:fromYDelta="0"
android:toXDelta="0"
android:toYDelta="-100%"
android:duration="500"/>
</set>
具體動畫程式碼 進入
<set xmlns:android="http://schemas.android.com/apk/res/android"> <translate android:fromXDelta="0" android:fromYDelta="100%" android:toXDelta="0" android:toYDelta="0" android:duration="500"/> </set>
activity程式碼
@BindView(R.id.ts_test) TextSwitcher ts_test; String[] str={ "第一個", "第二個", "第三個", "第四個" }; int cur; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_swicher); ButterKnife.bind(this); ts_test.setFactory(new ViewSwitcher.ViewFactory() { @Override public View makeView() { final TextView tv=new TextView(SwicherTestActivity.this); tv.setTextSize(25); tv.setTextColor(Color.RED); tv.setGravity(Gravity.CENTER); //設定點選事件 tv.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Toast.makeText(SwicherTestActivity.this,cur+tv.getText().toString(),Toast.LENGTH_SHORT).show(); } }); return tv; } }); } public void next(View view){ //切換到下一內容,有動畫 ts_test.setText(str[cur++%str.length]); //設定立刻生效當前的內容,沒有動畫展示. // ts_test.setCurrentText(str[cur++%str.length]); }