2011-02-16 86 views
9

我一直在嘗試將TextView和EditText合併爲一個複合控件,該複合控件使用自定義xml元素爲每個單獨元素傳遞默認值。我一直在尋找教程/這裏文檔:
Building Compound Controls
Passing Custom Attributes使用自定義XML屬性創建複合控件

我有什麼事這麼遠。

Attrs.xml:

<?xml version="1.0" encoding="utf-8"?> 
<resources> 
    <declare-styleable name="FreeText"> 
     <attr name="label" format="string" /> 
     <attr name="default" format="string" /> 
    </declare-styleable> 
</resources> 

我主要佈局:

<?xml version="1.0" encoding="utf-8"?> 
<LinearLayout 
    xmlns:android="http://schemas.android.com/apk/res/android" 
    xmlns:myapp="http://schemas.android.com/apk/res/android" 
    android:orientation="vertical" 
    android:layout_width="fill_parent" 
    android:layout_height="fill_parent" 
    > 
    <com.example.misc.FreeText 
     android:layout_width="fill_parent" 
     android:layout_height="wrap_content" 
     myapp:label="label" 
     myapp:default="default" 
    /> 
</LinearLayout> 

我的複合控制,FreeText的:

public class FreeText extends LinearLayout { 

    TextView label; 
    EditText value; 

    public FreeText(Context context, AttributeSet attrs) { 
     super(context, attrs); 

     this.setOrientation(HORIZONTAL); 

     LayoutParams lp = new LayoutParams(0, LayoutParams.WRAP_CONTENT); 
     lp.weight = 1; 

     label = new TextView(context); 
     addView(label, lp); 

     value = new EditText(context); 
     addView(value, lp); 

     TypedArray a = context.obtainStyledAttributes(attrs, R.styleable.FreeText); 
     CharSequence s = a.getString(R.styleable.FreeText_label); 
     if (s != null) { 
      label.setText(s); 
     } 

     a.recycle(); 
    } 
} 

當我運行程序我看到了意見確定,但我的CharSequence的值始終爲空。有人能告訴我我要去哪裏嗎?

回答

7

我討厭它,當你發現問題後,你尋求幫助。

的問題是,我對我的自定義XML元素的命名空間應該是像這樣:

<?xml version="1.0" encoding="utf-8"?> 
<LinearLayout 
    xmlns:android="http://schemas.android.com/apk/res/android" 
    xmlns:myapp="http://schemas.android.com/apk/res-auto" 
    android:orientation="vertical" 
    android:layout_width="fill_parent" 
    android:layout_height="fill_parent" 
    > 
    <com.example.misc.FreeText 
     android:layout_width="fill_parent" 
     android:layout_height="wrap_content" 
     myapp:label="label" 
     myapp:default="default" 
    /> 
</LinearLayout> 
+1

我尋求幫助,之後愛你注意到這個問題的事實,而不是之前!你在別處爲我解決了相同的問題。謝謝! – gregko 2015-04-20 18:58:38