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