17

私のカスタム ビューには動的なカスタム属性があります。コンストラクタ 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

-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 に答える