2011-02-16 88 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