是否可以将ViewFlipper扩展为自定义视图,以便在预览中更改初始页面?

S.B*_*oni 6 java android viewflipper android-view kotlin

是否可以将a 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
  }
}
Run Code Online (Sandbox Code Playgroud)

S.B*_*oni 5

更新:我自己找到了答案,不知道是否有更好的解决方案,这是我所做的:

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()
    }
}
Run Code Online (Sandbox Code Playgroud)

在res / values / attrs.xml中,我添加了属性displayChild

<resources>
    <declare-styleable name="ViewFlipperEng">
        <attr name="displayedChild" format="integer" />
    </declare-styleable>
</resources>
Run Code Online (Sandbox Code Playgroud)

要使用此新的“自定义”视图,只需在您的布局中使用:

<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>
Run Code Online (Sandbox Code Playgroud)