android:如何使用attributeset构造函数实例化我的自定义视图

时间:2011-04-28 08:49:26

标签: android dynamic attributes custom-view

我的自定义视图具有动态自定义属性,例如。 backgroundimage属性,通过当前周分配。 我不想使用construtor CalendarView(Context context,AttributeSet attrs)传递几个属性,我尝试使用Xml.asAttributeSet实例化attributeset,但它无法工作。任何人都可以告诉我该怎么做。

注意:我的自定义视图具有动态属性,因此我不想通过xml布局实例化自定义视图。我的解决方案不正确?

这是自定义视图:

public class CalendarView extends View {
    int backgroundImage;
    public CalendarView(Context context, AttributeSet attrs) {
        super(context, attrs);
        backgroundImage = attrs.getAttributeResourceValue("http://www.mynamespace.com", "backgroundimage", 0); 
    }
}

这是活动:

public class TestActivity extends Activity {

    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(createTestView(0));
    }


public CalendarView createTestView(int currentWeek) throws XmlPullParserException, IOException {
    String attributes = "<attribute xmlns:android=\"http://schemas.android.com/apk/res/android\" " +
        "xmlns:test=\"http://www.mynamespace.com\" " +
        "android:layout_width=\"fill_parent\" android:layout_height=\"30\" " +
        "test:backgroundimage=\"@drawable/"+ currentWeek +"_bg" + "\"/>";

    XmlPullParserFactory factory = XmlPullParserFactory.newInstance();          
    factory.setNamespaceAware(true);
    XmlPullParser parser = factory.newPullParser();
    parser.setInput(new StringReader(attributes));
    parser.next();
    AttributeSet attrs = Xml.asAttributeSet(parser);
    return new CalendarView(this,attrs);
}
}

2 个答案:

答案 0 :(得分:0)

您必须在位于值

的attr.xml文件中将该属性声明为styleable

例如:

<declare-styleable name="yourView">
    <attr name="aAttr" format="dimension" />
    <attr name="bAttr" format="dimension" />
   >

之后,您必须在自定义视图中使用它们,并且必须声明两个默认构造函数:

  public CalendarView(Context context) {
     super(context);
   }

public CalendarView(Context context, AttributeSet attrs) {
    super(context, attrs);
    backgroundImage = attrs.getAttributeResourceValue("http://www.mynamespace.com", 
   "backgroundimage", 0); 
    int typefaceIndex = attrs.getAttributeIntValue("http://schemas.android.com/apk/res/android", "typeface", 0);
    TypedArray a = context.obtainStyledAttributes(attrs, R.styleable.yourView);
}

这应该有效,可以获取自定义视图的参数。随意询问您是否不在身边。

typeFaceindex只是一个有效的例子。

之后你必须像其他任何一样使用你的customView布局:

<com.example.yourView> </com.example.yourView>

答案 1 :(得分:-1)

也许我不知道你在做什么或为什么这样做,但我发现你对AttributeSet的尝试非常复杂。

我建议你创建另一个这样的构造函数

public CalendarView(Context context, int backgroundRessourceID) {
    super(context);

    setBackgroundResource(backgroundRessourceID);
}

然后像这样实例化您的CalendarView

CalendarView cv = new CalendarView(this, R.drawable.0_bg);
cv.setLayoutParams(new LayoutParams(LayoutParams.MATCH_PARENT, 30));

希望这能解决你的问题...

相关问题