TextSwitcher的使用

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;

	@Override
	protected 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() {

			@Override
			public void onClick(View v) {
				// 为TextSwitcher设置显示内容
				switcher.setText(String.valueOf(new Random().nextInt()));
			}
		});
	}

	@Override
	public 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>



 

原文地址:https://www.cnblogs.com/bbsno1/p/3266561.html