2010-10-15 75 views
15

我使用GWT和UiBinder的我的應用程序,我試圖做到這一點風俗UiBinder的屬性部件

<g:TextBox ui:field="searchBox" styleName="{style.searchBox}" placeholder="search" />

但自定義屬性placeholder將無法​​工作,因爲沒有在TextBox一個setPlaceholder方法 - 我需要這樣的:

searchBox.getElement().setAttribute("placeholder", "search");

早在Java代碼。關於如何在UiBinder本身做到這一點的想法?我想我可以將它改爲正常的輸入元素,並嘗試獲取參考及其價值,但我寧願不走那條路。

+0

Afaik這是不可能的(正如你所說,你需要一個setter方法)。爲什麼不在調用'initWidget(uiBinder.createAndBindUi(this))'後立即在相應視圖類的構造函數中設置屬性?編輯:或編寫自己的佔位符功能,也可以在舊版瀏覽器上使用。 – z00bs 2010-10-15 07:49:15

+0

'initWidget'就是我現在調用'setAttribute'的地方......我不想將演示文稿移出XML文件...... – 2010-10-15 14:25:32

回答

14

如何創建自定義SearchBox,延長TextBox與方法setPlaceholder(String placeholder)

然後在UiBinder的:

<custom:SearchBox ui:field="searchBox" styleName="{style.searchBox}" placeholder="search" />

+2

這可能是我最終會在這種情況下做的事情,但我發現使用基於屬性的HTML 5功能變得越來越困難:( – 2010-10-15 14:24:26

8

關於在此之後一年就被問,我有必要使用自定義屬性(佔位符,特別是)。所以我寫了以下自定義TextField類,它擴展了TextBox,保留了GWT TextBox的所有基礎功能,包括處理程序等。希望有人在他們的搜索中絆倒這一點。 :)

public class TextField extends TextBox { 

    String placeholder = ""; 

    /** 
    * Creates an empty text box. 
    */ 
    public TextField() {} 

    /** 
    * Gets the current placeholder text for the text box. 
    * 
    * @return the current placeholder text 
    */ 
    public String getPlaceholder() { 
     return placeholder; 
    } 

    /** 
    * Sets the placeholder text displayed in the text box. 
    * 
    * @param placeholder the placeholder text 
    */ 
    public void setPlaceholder(String text) { 
     placeholder = (text != null ? text : ""); 
     getElement().setPropertyString("placeholder", placeholder); 
    } 
} 
+3

您不需要將佔位符作爲java變量存儲,您可以直接使用DOM值。 – logan 2012-11-06 22:47:37