Android中TextSwitcher的功能与用法

TextSwitcher继承了ViewSwitcher,因此它具有与ViewSwitcher相同的特征,TextSwitcehr需要设置一个ViewFactory,其中的makeView方法还需返回一个TextView组件。

下面是界面布局XML文件:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context="com.example.home.androidapptest.MainActivity">
    <!--定义了一个TextSwitcher,并指定了文本切换时的动画效果-->
    <TextSwitcher
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:id="@+id/textSwitcher"
        android:inAnimation="@android:anim/slide_in_left"
        android:outAnimation="@android:anim/slide_out_right"
        android:onClick="next">
    </TextSwitcher>
</LinearLayout>
上面的布局文件中定义了一个TextSwitcher,并指定了文本切换时的动画效果,接下来只要为TextSwitcher设置ViewFacrory。Activity代码如下:


public class MainActivity extends AppCompatActivity {
    TextSwitcher textSwitcher;
    String[] strs=new String[]{
            "疯狂Java讲义",
            "疯狂Android讲义",
            "疯狂ajax讲义",
            "轻量级Java EE企业应用实战"
    };
    int curStr;
    @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 tv=new TextView(MainActivity.this);
                tv.setTextSize(40);
                tv.setTextColor(Color.MAGENTA);
                return tv;
            }
        });
        //调用next方法显示下一个字符串
        next(null);
    }
    //事件处理函数,控制显示下一个字符串
    public void next(View source){
        textSwitcher.setText(strs[curStr++%strs.length ]);
    }
}

  • 2
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值