2011-05-12 67 views
0

我正在學習在android中創建複合控件。 對於初學者,我嘗試了一個帶有附加按鈕的編輯文本來清除它。在Android中創建複合控件的問題

問題是,即使我可以在 main.xml的圖形視圖中看到複合控件,但仍有一個錯誤消息:「自定義視圖ClearableEditText未使用2或3參數的View構造函數; XML屬性將不起作用「 這是不可見的項目瀏覽器中的錯誤只在xml圖形視圖 我能夠編譯和運行,但得到一個力量關閉。

XML:複合控制clearable_edit_text.xml

<?xml version="1.0" encoding="utf-8"?> 
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" 
    android:orientation="vertical" 
    android:layout_width="fill_parent" 
    android:layout_height="fill_parent" 
> 
    <EditText android:id="@+id/editText" 
     android:layout_width="fill_parent" 
     android:layout_height="wrap_content" 
    /> 
    <Button android:id="@+id/clearButton" 
     android:layout_width="wrap_content" 
     android:layout_height="wrap_content" 
     android:text="CLEAR" 
    /> 
</LinearLayout> 

CLASS

public class ClearableEditText extends LinearLayout 
{ 
    EditText et; 
    Button btn; 

    public ClearableEditText(Context context) 
    { 
     super(context); 
     LayoutInflater li=(LayoutInflater)getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE); 
     li.inflate(R.layout.clearable_edit_text,this,true); 

     et=(EditText)findViewById(R.id.editText); 
     btn=(Button)findViewById(R.id.clearButton); 

     hookupButton(); 
    } 

    private void hookupButton() 
    { 
     btn.setOnClickListener(new Button.OnClickListener() 
     { 
      public void onClick(View v) 
      { 
       et.setText(""); 
      } 
     }); 
    } 
} 

main.xml中

<?xml version="1.0" encoding="utf-8"?> 
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" 
    android:orientation="vertical" 
    android:layout_width="fill_parent" 
    android:layout_height="fill_parent" 
> 
    <com.commsware.android.merge.ClearableEditText 
     android:layout_width="fill_parent" 
     android:layout_height="wrap_content" 
    /> 
    <com.commsware.android.merge.ClearableEditText 
     android:layout_width="fill_parent" 
     android:layout_height="wrap_content" 
    /> 
</LinearLayout> 

回答

1

你的類擴展LinearLayout但你永遠不添加任何的意見吧。您需要撥打addView(...)並傳遞您的虛擬視圖作爲參數。

此外,要定義您的XML視圖,您需要覆蓋LinearLayout的2和3參數構造函數。添加到您的代碼:

public ClearableEditText(Context context, AttributeSet attrs) { 

    super(context, attrs); 
} 

public ClearableEditText(Context context, AttributeSet attrs, int defStyle) { 

    super(context, attrs, defStyle); 
} 

要獲得所有3個構造使用相同的初始化代碼,從單參數的構造函數移動你的代碼到3參數的構造函數,然後在其他2層的構造分別叫this(context, null, 0)this(context, attrs, 0)

+0

似乎是一個3參數的構造函數不存在於LinearLayout中,它表示構造函數沒有被定義。所以我只使用了1和2個參數構造函數,並且該應用程序工作。 – Deepak 2011-05-13 08:48:26

+0

我試圖在main中使用標籤,正如我爲qst研究的差異主題中所建議的,以移除LinearLayout。當我這樣做時,複合組件的唯一一個實例顯示其餘部分不可見。 – Deepak 2011-05-13 09:03:37