Android中自定义组件和它的属性

好长时间没有更新博客了,本来想积累点有深度的东西发,但一直没有找到很好的点。所以,写一些基础的东西,就当积累吧。
Android开发中难免会用到自定义的组件,下面以ImageButton为例来介绍怎么自定义组件和它的属性:

第一步、在values/attrs.xml中为组件自定义属性:
<?xml version="1.0" encoding="utf-8"?>
<resources>
    <declare-styleable name="CustomBtn">
        <attr name="text" format="string"/>
        <attr name="textColor" format="color" />
        <attr name="textSize" format="dimension" />
    </declare-styleable>
</resources>

第二步、重写ImageButton类:
public class CustomBtn extends ImageButton
{
 private Paint paint;
 private String text;
 
 public CustomBtn(Context context, AttributeSet attrs)
 {
  super(context, attrs);
 
  paint=new Paint();
  TypedArray typeArray=context.obtainStyledAttributes(attrs,R.styleable.CustomBtn);
  int color=typeArray.getColor(R.styleable.CustomBtn_textColor,Color.WHITE);
  float textSize=typeArray.getDimension(R.styleable.CustomBtn_textSize,20);
  text=typeArray.getString(R.styleable.CustomBtn_text);
 
  paint.setTextAlign(Align.CENTER);
  paint.setColor(color);
  paint.setTextSize(textSize);
  typeArray.recycle();
 }
 
 @Override
 protected void onDraw(Canvas canvas)
 {
  super.onDraw(canvas);
  canvas.drawText(text,canvas.getWidth()/2,canvas.getHeight()/2+10, paint);
 }

 public String getText() {
  return text;
 }

 public void setText(String text) {
  this.text = text;
 }
}

第三步、在布局文件中使用CustomBtn:
其中xmlns:custombtn中为AndroidManifest.xml中的包名

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:custombtn="http://schemas.android.com/apk/res/com.yeahis.shuyudragstore"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="@dimen/market_category_height"
android:background="@drawable/mall_category_item">

<com.yeahis.shuyudragstore.widget.CustomBtn
android:id="@+id/mall_category_btn"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_alignParentLeft="true"
android:background="@android:color/transparent"
android:src="@drawable/mall_category_title"
custombtn:text="@string/mall_category_title"
custombtn:textColor="@android:color/black"
custombtn:textSize="15sp"/>

</RelativeLayout>

第四步、如果想要在程序中动态改变 CustomBtn上的文字则在程序中这样:
例如CustomBtn customBtn=(CustomBtn) convertView.findViewById(R.id.mall_category_btn);

customBtn.setText("在程序中添加的文字");


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值