android 使用attrs自定义控件

步骤:

1、在values下新建一个attrs.xml的资源文件(my_attrs.xml)

       <declare-styleable name="My_attrs">    //===》name为引用资源的名称

          // attr中的 name为自定义的名称   format 为类型

           <attr name="TextColor" format="color"></attr>  // 字体颜色 
            <attr name="TextSize" format="dimension"></attr>  //字体大小
            <attr name="Text" format="string"></attr>   //字符串
      </declare-styleable>

2、新建一个类MyAttrsMyView继承 View

      覆写public MyAttrsMyView(Context context, AttributeSet attrs)方法

@SuppressLint("NewApi")
    public MyAttrsMyView(Context context, AttributeSet attrs) {
        super(context, attrs);
        // TODO Auto-generated constructor stub
        mPaint = new Paint();    //定义画笔
        imageView = new ImageView(context);   //图片
        imageView.setImageResource(R.drawable.ww);  //加载图片资源
        TypedArray a = context.obtainStyledAttributes(attrs, R.styleable.My_attrs);    //获取自定义的attrs中的资源
        float textsize = a.getDimension(R.styleable.My_attrs_TextSize, 40);  
        int c = a.getColor(R.styleable.My_attrs_TextColor, 0x990000FF);
        s = a.getString(R.styleable.My_attrs_Text);
        mPaint.setColor(c);
        mPaint.setTextSize(textsize);
        a.recycle();  //结束标记
    }

@Override
    protected void onDraw(Canvas canvas) {
        // TODO Auto-generated method stub
        super.onDraw(canvas);
        
        //canvas.drawRect(new Rect(10, 10, 280, 200), mPaint);

       //((BitmapDrawable)imageView.getDrawable()).getBitmap() ;将imageview转换成bitmap

        canvas.drawBitmap(((BitmapDrawable)imageView.getDrawable()).getBitmap(), 1, 20, mPaint);
        //canvas.drawBitmap(BitmapFactory.decodeResource(getResources(), R.drawable.ww), 10, 10, mPaint);
        canvas.drawText(s, 1, 100, mPaint);
    }

3、最后一步

第一种写法    在activity中 , 直接new出自定义的类即可
          MyView = new MyAttrsMyView(this,null);
          setContentView(MyView);

   

第二种写法    利用xml
            1、在xml中  <com.ming.attrs.MyAttrsMyView  、、、、/>
         2、在其根布局 添加声明  :  xmlns:ymy(自己起的名)="http://schemas.android.com/apk/res/项目的主包名"
         3、给自定义的控件中添加attrs 中定义好的属性  :  ymy:Text = "顺丰快递"

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
     xmlns:ymy="http://schemas.android.com/apk/res/com.ming"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical" >
    <com.ming.attrs.MyAttrsMyView
        android:layout_width="400dp"   
        android:layout_height="300dp"
        ymy:TextColor = "#ABCDEFEF"
        ymy:Text = "顺丰快递"
        ymy:TextSize = "12sp"

        />
</LinearLayout>



  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值