你們大多數人都會知道在Android中爲自定義視圖提供自定義屬性的可能性。這個例子在this thread here on Stackoverflow中有很好的解釋。然而,我的問題是:是否可以在自定義android屬性上有條件語句?
只有在滿足另一個條件時纔可以顯示這些屬性嗎?
我的意思是這樣的(僞代碼):
<?xml version="1.0" encoding="utf-8"?>
<resources>
<declare-styleable name="MyCustomView">
<attr name="isClock" format="boolean" />
</declare-styleable>
<if name="isClock" value="true">
<attr name="timezone" format="string">
</if>
<else>
<attr name="somethingElse" format="string>
</else>
</resources>
現在一個可能性,沒有與「錯」的工作屬性就是做這在Java的代碼,明明:
public class MyCustomView {
public MyCustomView(Context context) {
TypedArray styleables = context.obtainStyledAttributes(attrs, R.styleable.MyCustomView);
boolean choice = styleables.getBoolean(R.styleable.MyCustomView_isClock, false);
if(choice) {
// It's a clock, react to the other attrs
} else {
// Don't react
}
styleables.recycle();
}
}
另一種方式是做什麼ilomambo在他的答案建議:不同的名稱創建不同的自定義視圖,並讓他們只屬於他們的屬性。
但是我非常想問問自己是否有可能不首先將.xml-File的程序員混淆,只給他提供他真正需要的東西。畢竟這個是以已經由Android(well ... IDE/Lint/Parser ...)完成的方式,例如當使用layout_weight
時應該將視圖的寬度或高度設置爲0dp
。
但是,如果我不得不猜測,我會說這可能是唯一可能的,如果我重寫Android XML解析器...有人可以證明我錯了嗎?
在此先感謝
你在做什麼是錯的 – Raghunandan
「只有在滿足另一個條件時纔有可能呈現這些屬性嗎?」 - AFAIK,沒有。 – CommonsWare