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:andro
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:
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("在程序中加入的文字");