2011-08-08 62 views
0

我创建了一个包含TextView和一个扩展了LinearLayout(称为LabeledSpinner)的Spinner的自定义布局。 我把这些LabeledSpinners中的几个放入我的主RelativeLayout中,显然我想为每个textview设置不同的文本,但我不知道如何在xml文件中执行它。访问自定义布局的内部视图的属性

我需要以某种方式访问​​内部视图的属性,请帮助。 我试图用[包名] .LabeledSpinner.label:文本,但它没有工作

(标签是的TextView的id)

回答

1

让LabeledSpinner一个设置样式(RES /价值/ attrs.xml )

<declare-styleable name="LabeledSpinner"> 
    <attr name="text" format="string"/> 
</declare-styleable> 

在你LabeledSpinner

public LabeledSpinner(Context context, AttributeSet attrs, int defStyle) { 
    super(context, attrs, defStyle); 
    TypedArray a = context.obtainStyledAttributes(attrs, R.styleable.LabeledSpinner); 
    String text = a.getString(R.styleable.LabeledSpinner_text); 
    a.recycle(); 
} 

注意,在LabeledSpinnertext属性是用作LabeledSpinner_text

现在,在您的布局

<LinearLayout 
    xmlns:android="http://schemas.android.com/apk/res/android" 
    xmlns:yourpackage="http://schemas.android.com/apk/res/com.package"> 
    <com.package.LabeledSpinner 
     android:layout_width="wrap_content" 
     android:layout_height="wrap_content" 
     yourpackage:text="This is where your text goes"/> 
</LinearLayout> 

这应该做的!