欢迎来到尧图网

客户服务 关于我们

您的位置:首页 > 汽车 > 时评 > 【安卓学习】文本切换器

【安卓学习】文本切换器

2024/10/24 7:29:51 来源:https://blog.csdn.net/m0_73241073/article/details/140267991  浏览:    关键词:【安卓学习】文本切换器

TextSwitcher

TextSwitcher 是 ViewSwitcher 的 子 类, 它 与 ImageSwitcher 很 相 似, 都 需 要 设 置 一 个ViewFactory,并且都可以设置切换时所显示的动画效果。不同的是 TextSwitcher 在实现 ViewFactory接口中的 makeView() 方法时,需要返回一个 TextView 组件。

基本语法

<TextSwitcherandroid:id="@+id/textSwitcher"android:layout_width="match_parent"android:layout_height="wrap_content"/>

支持的属性

支持的属性

实例

XML

<?xml version="1.0"encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"xmlns app="http://schemas.android.com/apk/res-auto"xmlns tools="http://schemas.android.com/tools"android:layout_width="match_parent"android:layout_height="match_parent"android:background="@mipmap/bg"tools context="com.mingrisoft.MainActivity"><!--定义文本切换器并设置文本切换时的动画效果--><TextSwitcherandroid:id="@+id/textSwitcher"android:layout_width="260dp"android:layout_height="100dp"android:layout_marginTop="50dp"android:layout_marginLeft="50dp"android:inAnimation="@anim/in_animation"android:outAnimation="@anim/out_animation"></Textswitcher>
</RelativeLayout>

注意:在XML文件中设置TextSwitcher组件时,需要指定文字切换时进入与退出的动画文件,如代码中的“anim/in_animation”文字切换时的进入动画文件,“anim/out_animation”文字切换时的退出动画文件。这两个动画文件需要手动创建

Activity

public class MainActivity extends Activity{//定义文本切换器private TextSwitcher textSwitcher;//定义用于计算诗句数组下标private int index;//定义唐诗数组String[] poetry = new String[]{"望庐山瀑布""[作者]李白""日照香炉生紫烟,""避看瀑布挂前川。""飞流直下三千尺,""疑是银河落九天。"};@Overrideprotected void onCreate(Bundle savedInstancestate){super.onCreate(savedInstancestate);setContentview(R.layout.activity_main);}
}

在主活动的 onCreate() 方法中,首先获取布局文件中的 TextSwitcher 组件,然后为其设置1 个 ViewFactory,并重写makeView() 方法,最后在重写的 makeView() 方法中创建 1 个用于显示唐诗文字的 TextView。

	//获取文本切换器组件textSwitcher (TextSwitcher)findviewById(R.id.textswitcher);//为文本切换器设置FactorytextSwitcher.setFactory(new ViewSwitcher.ViewFactory(){@Overridepublic View makeview(){//创建文本框组件用于显示唐诗文字Textview textview = new Textview(MainActivity.this);textView.setTextsize(30);//设置文字大小textView.setTextColor(Color.BLACK);//设置文字颜色为黑色return textView;}
})

重写onTouchEvent()方法,在该方法中实现单击手机或模拟器屏幕时切换显示的唐诗文字。具体代码如下:

@Override
public boolean onTouchEvent(MotionEvent event){//判断手指单击屏幕时if (event.getAction()==MotionEvent.ACTION_DOWN){//切换显示的诗句文字textSwitcher.setText(poetry[index++%poetry.length ])return super.onTouchEvent(event);
}

运行结果

在这里插入图片描述

版权声明:

本网仅为发布的内容提供存储空间,不对发表、转载的内容提供任何形式的保证。凡本网注明“来源:XXX网络”的作品,均转载自其它媒体,著作权归作者所有,商业转载请联系作者获得授权,非商业转载请注明出处。

我们尊重并感谢每一位作者,均已注明文章来源和作者。如因作品内容、版权或其它问题,请及时与我们联系,联系邮箱:809451989@qq.com,投稿邮箱:809451989@qq.com