Android自定义View

1. 继承自android.view.View.

2. 自定义属性

3. 重写onMeasure() 和 onDraw()

1. 继承自View

class PieChart extends View {
    public PieChart(Context ctx, AttributeSet attrs) {
        super(ctx, attrs);
    }
}

2. 自定义属性

  • 在<declare-styleable>中声明属性
  • 在xml layout文件中设置这些属性
  • 程序运行的时候取得这些属性
  • 设置这些属性到我们自定义的view中去


   在<declare-styleable>中声明属性:

<resources>
   <declare-styleable name="PieChart">
       <attr name="showText" format="boolean" />
       <attr name="labelPosition" format="enum">
           <enum name="left" value="0"/>
           <enum name="right" value="1"/>
       </attr>
   </declare-styleable>
</resources>


在xml layout文件中设置这些属性

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
   xmlns:custom="http://schemas.android.com/apk/res/com.example.customviews">
 <com.example.customviews.charting.PieChart
     custom:showText="true"
     custom:labelPosition="left" />
</LinearLayout>


custom:namespace的名字

http://schemas.android.com/apk/res/com.example.customviews
=  http://schemas.android.com/apk/res/[your package name]


程序运行的时候取得这些属性

public PieChart(Context ctx, AttributeSet attrs) {
   super(ctx, attrs);
   TypedArray a = context.getTheme().obtainStyledAttributes(
        attrs,
        R.styleable.PieChart,
        0, 0);

   try {
       mShowText = a.getBoolean(R.styleable.PieChart_showText, false);
       mTextPos = a.getInteger(R.styleable.PieChart_labelPosition, 0);
   } finally {
       a.recycle();
   }
}

设置这些属性到我们自定义的view中去

上面得到自定义的属性之后,就可以在我们的程序中去使用它们了,比如

public boolean isShowText() {
   return mShowText;
}

public void setShowText(boolean showText) {
   mShowText = showText;
   invalidate();
   requestLayout();
}

3. 重写onMeasure() 和 onDraw()

@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
setMeasuredDimension(resolveSize(getSuggestedMinimumWidth(), widthMeasureSpec),resolveSize(getSuggestedMinimumHeight(), heightMeasureSpec));
}




转载于:https://my.oschina.net/scuping/blog/486634

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值