這篇文章主要介紹“Android如何在xml中設(shè)置自定義屬性”的相關(guān)知識,小編通過實際案例向大家展示操作過程,操作方法簡單快捷,實用性強(qiáng),希望這篇“Android如何在xml中設(shè)置自定義屬性”文章能幫助大家解決問題。
1. 在項目中的values文件中創(chuàng)建attrs文件
2. 在view中關(guān)聯(lián)這些屬性
public class MyView extends LinearLayout { private int mIndicatorColor,mIndicatorId; private String mIndicatorText; public MyView(Context context, AttributeSet attrs, int defStyleAttr) { super(context, attrs, defStyleAttr); //從xml的屬性中獲取到值,然后想怎么用就怎么用 TypedArray ta=context.obtainStyledAttributes(attrs,R.styleable.QLoadingIndicatorView); mIndicatorColor=ta.getColor(R.styleable.QLoadingIndicatorView_indicatorColor,Color.BLACK);//第二個參數(shù)是設(shè)置的默認(rèn)值,當(dāng)你不設(shè)置這個屬性時會使用這個值 mIndicatorId=ta.getInt(R.styleable.QLoadingIndicatorView_indicatorId,1); mIndicatorText=ta.getString(R.styleable.QLoadingIndicatorView_indicatorText,"abc"); ta.recycle(); } }
3.xml文件中設(shè)置屬性和命名空間
關(guān)于“Android如何在xml中設(shè)置自定義屬性”的內(nèi)容就介紹到這里了,感謝大家的閱讀。如果想了解更多行業(yè)相關(guān)的知識,可以關(guān)注創(chuàng)新互聯(lián)行業(yè)資訊頻道,小編每天都會為大家更新不同的知識點(diǎn)。