Android中自訂群組件和它的屬性

來源:互聯網
上載者:User

標籤: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中自訂群組件和它的屬性

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.