栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

自定义View学习之---->自定义TextView

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

自定义View学习之---->自定义TextView

文章是视频学习中的笔记,和一些代码示例。

1:自定义view的三个构造函数分别在什么时候调用

public class MyTextView extends TextView {

    //构造函数会在代码中new的时候调用
    // MyTextView textView=new MyTextView(this);
    public MyTextView(Context context) {
        super(context);
    }

    //在布局layout中使用
    // 
    public MyTextView(Context context, @Nullable AttributeSet attrs) {
        super(context, attrs);
    }
    //在布局layout中使用 但是会有style
    //    
    public MyTextView(Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        //获取自定义属性
    }

}

2:自定义TextView的属性,现在res下创建一个attrs.xml (名称可以随便取,但最好是这个名字)



    
    
        
        
        
        
        
    

3:在layout文件中使用attrs中对应的属性

        首先在根布局中添加

        xmlns:app="http://schemas.android.com/apk/res-auto"

       接下来就可以使用自定义的属性了

        

4:接下来重写MyTextView的super,然后获取自定义属性

public class MyTextView extends TextView {
    private String mText;
    private int mTextSize;

    //构造函数会在代码中new的时候调用
    // MyTextView textView=new MyTextView(this);
    public MyTextView(Context context) {
//        super(context);
        this(context, null);//使用这种方式会调用第二个构造函数
    }

    //在布局layout中使用
    // 
    public MyTextView(Context context, @Nullable AttributeSet attrs) {
//        super(context, attrs);
        this(context, attrs, 0);//使用这种方式会调用第三个构造函数,这样就可以只在第三个构造函数中获取自定义属性
    }

    //在布局layout中使用 但是会有style
    //    
    public MyTextView(Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        //获取自定义属性

        TypedArray array = context.obtainStyledAttributes(attrs, R.styleable.MyTextView);
        mText = array.getString(R.styleable.MyTextView_text);
        mTextSize = array.getDimensionPixelSize(R.styleable.MyTextView_textSize, mTextSize);

        array.recycle();
    }

}

目前仅写到此处,后续更新

        

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/293169.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号