標籤:android style http color io 使用 ar for 檔案
好長時間沒有更新部落格了,本來想積累點有深度的東西發,但一直沒有找到很好的點。所以,寫一些基礎的東西,就當積累吧。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, paint); }}
第三步、在布局檔案中使用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.CustomBtnandroid: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>
Android中自訂群組件和它的屬性