17

我的自定义视图具有动态自定义属性,例如 backgroundimage 属性,通过当前周分配。我不想使用构造函数 CalendarView(Context context, AttributeSet attrs) 来传递几个属性,我尝试用 Xml.asAttributeSet 实例化属性集,但它不起作用。谁能告诉我该怎么做。

注意:我的自定义视图具有动态属性,所以我不想通过 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);
}
}
4

2 回答 2

0

您必须在 attr.xml 文件中将属性声明为可设置样式

例如:

<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>
于 2014-05-08T13:21:08.377 回答
-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));

希望这可以解决您的问题...

于 2011-04-28T09:35:29.790 回答