2013-08-20 169 views
1

我想創建自定義Android視圖(MyCustomView)。在此查看我想擁有自定義類型的屬性(MyCustomType)。類似於:自定義Android視圖的自定義類型屬性

MyCustomView extends LinearLayout { 

    private MyCustomType prop1; 

    public MyCustomType getProp1() 
    { 
     return this.prop1; 
    } 

    public void setProp1(MyCustomType value) 
    { 
     this.prop1 = value;} 
    } 
} 

到目前爲止好。但是現在我想能夠從XML設置這個屬性的值。我可以使用字符串,int,引用格式創建一個自定義屬性,但我看不到如何將此屬性定義爲MyCustomType格式。我形象的東西類似於此:

<declare-styleable name="MyCustomView"> 
    <attr name="prop1" format="MyCustomType"/> 
</declare-styleable> 

這是可能以某種方式?或者自定義類型屬性可能只能從代碼後面設置

謝謝!

+0

感謝您的評論,但是對於從XML設置的CUSTOM TYPE屬性沒有任何幫助。只有一個參考如何創建一個類型的字符串,整數,布爾值,引用等自定義屬性請仔細閱讀問題。 –

+0

好的。你不能。看到我的回答 –

回答

0

不能與Android框架使用自己的財產類型。你可以用自己的proprties根據可用類型但就是這樣。不知道你的情況是什麼類型,但在大多數情況下,無論這種習慣是什麼,它都可以通過可用的基元來解決。

+0

好的 - 謝謝你的時間! –

1

我真的不明白你爲什麼需要這個。但是您可以使用format =「String」並在佈局的屬性字段中編寫完整的類名稱。例如: 定製:爲prop1 = 「com.example.MyCustomType」

然後在視圖的構造函數:

TypedArray a = context.getTheme().obtainStyledAttributes(
    attrs, 
    R.styleable.MyCustomView, 
    0, 0); 
String className = a.getString(R.id.prop1); 
Class<MySustomType> c = Class.forName(className); 
MySustomType prop = c.newInstance(); 
setProp1(prop);