2013-04-18 27 views
3

你們大多數人都會知道在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解析器...有人可以證明我錯了嗎?

在此先感謝

+0

你在做什麼是錯的 – Raghunandan

+1

「只有在滿足另一個條件時纔有可能呈現這些屬性嗎?」 - AFAIK,沒有。 – CommonsWare

回答

1

如果我理解你的權利,你有一個自定義視圖,可以得到不同的屬性,第三屬性conditonal。

爲了保持XML程序員知道違法的屬性,我建議以下兩種方法之一:

  1. (簡單的方法),爲每個「名字」和每個自己的declare-styleable組一個自定義視圖。

    <resources> 
        <declare-styleable name="ClockCustomView"> 
         <attr . . . /> 
        </declare-styleable> 
        <declare-styleable name="OtherCustomView"> 
         <attr . . . /> 
        </declare-styleable> 
        <!-- Common attributes are declared outside declare-styleable --> 
        <attr . . . /> 
    </resources> 
    
  2. (更完整更復雜)爲您的XML的XSD架構,這樣程序員就可以驗證XML你的規則。 XSD本身就是XML,所以你只需要學習元素。有關XSD的更多信息,請參閱this link,如果您也是Google,則網絡上有許多信息。

+0

是的,你理解正確。方法1是我目前使用的臨時解決方案。我會盡快報告回XSD的時間,非常感謝你 – avalancha

+0

@avalancha請記住,方法#2你可以做你想做的事情以及更多。要付出的代價是你必須學會​​如何正確書寫。如果您使用Eclipse,那麼您會注意到,在編輯XML文件時,可以通過右鍵單擊上下文菜單進行驗證。 – ilomambo

相關問題