首页 > 学院 > 开发设计 > 正文

<TextView>实现一个有趣的小效果

2019-11-06 09:48:26
字体:
来源:转载
供稿:网友

假装它是动起来的,实现的是一个跑马灯效果 一、新建一个PRoject。

二、添加两个TextView,并设置它的属性。

<TextView android:id="@+id/tv_one" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="疯狂源自梦想,技术成就辉煌,好好学习,天天向上!!!" android:textSize="24dp" android:singleLine="true" android:ellipsize="marquee" android:focusable="true" android:focusableInTouchMode="true" android:textColor="#b1704a" /> <TextView android:layout_below="@+id/tv_one" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_marginTop="50dp" android:text="疯狂源自梦想,技术成就辉煌,好好学习,天天向上!!!" android:textSize="64dp" android:singleLine="true" android:ellipsize="marquee" android:focusable="true" android:focusableInTouchMode="true" android:textColor="#ff0000" />

android:singleLine=”true” 设置单行显示。 如果和layout_width一起使用,当文本不能全部显示时,后面用“…”来表示。


android:ellipsize=”marquee” .设置可滚动,或显示样式


android:focusable=”true”:设置TextView自动获得焦点 android:focusableInTouchMode=”true”:通过触摸获得焦点


这些属性设置完毕之后,运行一下,你会发现第一个TextView会有跑马灯效果,第二没有,这是因为程序一运行,先是第一个TextView或的焦点,一直没有丢失,所以第二个TextView才获取不到。也就没有效果。

如果需要两个TextView都能完美运行,自定义TextView,这时我们需要新建一个类来继承TextView。实现它的三个构造方法。并覆盖isFocused()方法,返回值设置为true,这样就强制性要求了这自定义TextView子类都获得焦点。

public class MarqueeText extends TextView{ public MarqueeText(Context context) { super(context); } public MarqueeText(Context context, AttributeSet attrs) { super(context, attrs); } public MarqueeText(Context context, AttributeSet attrs, int defStyleAttr) { super(context, attrs, defStyleAttr); } @Override public boolean isFocused() { return true; }}

然后我们在把TextView换成我们自定义的TextView,就OK了。

<com.zp.administrator.marqueetextviewdemo.MarqueeText android:id="@+id/tv_one" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="疯狂源自梦想,技术成就辉煌,好好学习,天天向上!!!" android:textSize="24dp" android:singleLine="true" android:ellipsize="marquee" android:focusable="true" android:focusableInTouchMode="true" android:textColor="#b1704a" /> <com.zp.administrator.marqueetextviewdemo.MarqueeText android:layout_below="@+id/tv_one" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_marginTop="50dp" android:text="疯狂源自梦想,技术成就辉煌,好好学习,天天向上!!!" android:textSize="64dp" android:singleLine="true" android:ellipsize="marquee" android:focusable="true" android:focusableInTouchMode="true" android:textColor="#ff0000" />

接着再运行就可以看到两个效果都实现了。

ps:今天是自己第一次写技术博客,虽然这只是开始的一小步,却是我作为程序员的一大进步。O(∩_∩)O~


发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表