Android——自定义控件(跑马灯实例)

说到自定义控件,自定义控件不仅能够让自己对控件的掌握更加熟悉,还可以实现很多功能,同时也可以节省出很多的时间!
人生中第一篇博客便是关于TextView跑马灯的实现,但是随着知识的增多,实现一些功能的方式方法也增多了起来,这里只是自定义控件一个例子,可以同理到很多控件上!

首先写一个类继承你需要重写的控件

比如我这里是MyTextView继承自TextView
只需要重写一些方法,就能达到和在XML页面设置属性一样的效果

public class MyTextView extends TextView{

    public MyTextView(Context context) {
        super(context);
    }

    //android:ellipsize="marquee" 重写此方法是为了让TextView具有跑马灯特性
    @Override
    public void setEllipsize(android.text.TextUtils.TruncateAt where) {
        super.setEllipsize(android.text.TextUtils.TruncateAt.MARQUEE);
    }

    //android:focusable="true"
    //android:focusableInTouchMode="true"  把此方法返回值改成true就可以获得焦点
    @Override
    public boolean isFocused() {
        return true;
    }

}
然后在XML页面只需要包名.类名就可以和正常控件一样使用~
<com.example.myapplication.PaoMaDeng.MyTextView
        android:textSize="20sp"
        android:layout_marginTop="20dp"
        android:id="@+id/txvpmd2"
        android:text="两次返回键才返回!    两次返回键才返回!    "
        android:layout_width="200dp"
        android:singleLine="true"
        android:marqueeRepeatLimit="marquee_forever"
        android:layout_height="wrap_content" />
发布了20 篇原创文章 · 获赞 40 · 访问量 6300

猜你喜欢

转载自blog.csdn.net/qq_44720366/article/details/104701287