在android中畫廊視圖Gallery和ImageSwitcher組件的使用
一文中介紹了ImageSwitcher的使用,在這裡簡單介紹一下TextSwitcher的使用,它和ImageSwitcher非常類似,都是繼承ViewSwitcher,只是TextSwitcher用於切換文本,代碼如下:
Activity:
package com.home.activity;import java.util.Random;import android.app.Activity;import android.graphics.Color;import android.os.Bundle;import android.view.Gravity;import android.view.View;import android.view.View.OnClickListener;import android.view.animation.Animation;import android.view.animation.AnimationUtils;import android.widget.Button;import android.widget.TextSwitcher;import android.widget.TextView;import android.widget.ViewSwitcher.ViewFactory;import com.home.textswitcher.R;public class TextSwitcherActivity extends Activity implements ViewFactory {private TextSwitcher switcher;private Button changeBtn;@Overrideprotected void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);setContentView(R.layout.main);switcher = (TextSwitcher) findViewById(R.id.main_ts);switcher.setFactory(this);// 設定淡入淡出的動畫效果Animation in = AnimationUtils.loadAnimation(this,android.R.anim.fade_in);Animation out = AnimationUtils.loadAnimation(this,android.R.anim.fade_out);switcher.setInAnimation(in);switcher.setOutAnimation(out);changeBtn = (Button) findViewById(R.id.main_btn_next);changeBtn.setOnClickListener(new OnClickListener() {@Overridepublic void onClick(View v) {// 為TextSwitcher設定顯示內容switcher.setText(String.valueOf(new Random().nextInt()));}});}@Overridepublic View makeView() {TextView tv = new TextView(this);tv.setTextSize(36);tv.setTextColor(Color.RED);tv.setGravity(Gravity.TOP | Gravity.CENTER_HORIZONTAL);return tv;}}
布局XML:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical" > <Button android:id="@+id/main_btn_next" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="切換" /> <TextSwitcher android:id="@+id/main_ts" android:layout_width="match_parent" android:layout_height="wrap_content" /></LinearLayout>