您可以将您的小部件定义为具有参数(例如handles
和contents
),每个参数都引用一个数组。您可以使用标准符号定义数组:
资源/值/arrays.xml
<array name="my_widget_layouts">
<item>@layout/contentLayout1</item>
<item>@layout/contentLayout2</item>
. . .
</array>
<array name="my_widget_buttons">
<item>@+id/slideHandleButton1</item>
<item>@+id/slideHandleButton2</item>
. . .
</array>
在一些布局内:
<com.example.MyWidget
ns:contents="@array/my_widget_layouts"
ns:handles="@array/my_widget/buttons"
. . .
/>
然后在构建小部件时的 Java 代码中:
MyWidget(Context context, AttributeSet attrs) {
Resources res = getResources();
TypedArray a = context.obtainStyledAttributes(attrs, R.styleable.MyWidget);
// Get the ID of the array containing the content layout IDs for this widget
int contentsId = a.getResourceId(R.styleable.MyWidget_contents, 0);
if (contentsId > 0) {
// array of layouts specified
TypedArray ta = res.obtainTypedArray(contentsId);
int n = ca.length();
mContentLayoutIds = new int[n];
for (int i = 0; i < n; ++i) {
mContentLayoutIds[i] = ta.getResourceId(i, 0);
// error check: should never be 0
}
ta.recycle();
}
// similar code to retrieve the button IDs
if (mContentLayoutIds.length != mHandleIds.length) {
// content layout and button arrays not same length: throw an exception
}
. . .
a.recycle();
. . .
}