是否可以将ViewFlipper
扩展为自定义View
,以便我可以为预览中显示的第一页设置xml属性?
要查看它是否有效,我尝试了一个应该在预览中显示第三页的示例,但它不起作用。这是kotlin的例子:
class ViewFlipperEng: ViewFlipper {
constructor(context: Context): super(context) {
init(context)
}
constructor(context: Context, attrs: AttributeSet): super(context, attrs) {
init(context)
}
private fun init(cxt: Context) {
displayedChild = 2
invalidate()
//also tried showNext or showPrevious
}
}
更新:我自己找到答案,不知道是否有更好的解决方案,这就是我所做的:
class ViewFlipperEng : ViewFlipper {
var initialPage:Int=0;
constructor(context: Context) : super(context){
initialPage=0
}
constructor(context: Context, attrs: AttributeSet): super(context, attrs){
if (attrs != null) {
// Attribute initialization
val a: TypedArray = context.obtainStyledAttributes(attrs, R.styleable.ViewFlipperEng, 0, 0);
initialPage = a.getInt(R.styleable.ViewFlipperEng_displayedChild,0);
}
}
override fun onAttachedToWindow()
{
displayedChild=initialPage
super.onAttachedToWindow()
}
}
在res / values / attrs.xml中我添加了属性displayedChild
<resources>
<declare-styleable name="ViewFlipperEng">
<attr name="displayedChild" format="integer" />
</declare-styleable>
</resources>
要在您的布局中使用这个新的自定义视图:
<com.yourpackage.ViewFlipperEng
android:id="@+id/view_flipper_example"
android:layout_width="match_parent"
app:displayedChild="2"
android:layout_height="match_parent">
...declare your views here (at least 3 views since we are using displayedChild="2")
</com.yourpackage.ViewFlipperEng>