Android 自定義view相關

Android 自定義view的四個構造函數什么情況下調用

  // 在new一個view的時會被調用
    public TestView7(Context context) {
        super(context);
    }
// 在xml中定義時會被調用(即使xml中的自定義view有使用自定義屬性,依然調用2個參數的構造方法)
    public TestView7(Context context, AttributeSet attrs) {
        super(context, attrs);
    }
// 自己手動調用才會被使用
    public TestView7(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
    }
// 自己手動調用才會被使用
    public TestView7(Context context, AttributeSet attrs, int defStyleAttr, int defStyleRes) {
        super(context, attrs, defStyleAttr, defStyleRes);
    }

Android 自定義view構造方法中的參數都是什么

Context:上線文

AttributeSet attrs : 從xml中定義的參數

int defStyleAttr   :自定義view的主題(主題中優先級最高的屬性)

int defStyleRes    :自定義view的風格(style中次于xml中定義的風格)

在android中的屬性可以在多個地方進行賦值,涉及到的優先級排序為:

Xml直接定義 > xml中style引用 > defStyleAttr > defStyleRes > theme直接定義

如何自定義view的屬性

Custom View添加自定義屬性主要是通過declare-styleable標簽為其配置自定義屬性,具體做法是: 在res/values
目錄下增加一個resources xml文件,示例如下(res/values/attrs_my_custom_view.xml): 

<resources>
    <declare-styleable name="MyCustomView">
        <attr name="custom_attr1" format="string" />
        <attr name="custom_attr2" format="string" />
        <attr name="custom_attr3" format="string" />
        <attr name="custom_attr4" format="string" />
    </declare-styleable>
    <attr name="custom_attr5" format="string" />
</resources

獲取自定義屬性

public MyCustomView(Context context, AttributeSet attrs, int defStyleAttr) {
    super(context, attrs, defStyleAttr);

    TypedArray ta = context.obtainStyledAttributes(attrs, R.styleable.MyCustomView);

    String attr1 = ta.getString(R.styleable.MyCustomView_custom_attr1);
    String attr2 = ta.getString(R.styleable.MyCustomView_custom_attr2);
    String attr3 = ta.getString(R.styleable.MyCustomView_custom_attr3);
    String attr4 = ta.getString(R.styleable.MyCustomView_custom_attr4);

    Log.e("customview", "attr1=" + attr1);
    Log.e("customview", "attr2=" + attr2);
    Log.e("customview", "attr3=" + attr3);
    Log.e("customview", "attr4=" + attr4);
    ta.recycle();
 }

使用自定義view的屬性值

在xml的根layout中引入命名空間
 xmlns:lsp="http://schemas.android.com/apk/res-auto"(lsp是自己起的名字)
在自己的view中使用
  android:padding="10dp"
  lsp:image="@mipmap/ic_launcher"
最后編輯于
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。

推薦閱讀更多精彩內容