Is it possible to extend a ViewFlipper as a custom View so to change the initial page in preview?
Asked Answered
R

1

8

Is it possible to extend a ViewFlipper as a custom View so that i could set an xml attribute for the first page to show in the preview?

To see if it works i tried an example that should show the third page in the preview, but it doesn't work. This is the example in 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
  }
}
Resurrectionism answered 10/4, 2019 at 9:52 Comment(0)
R
6

UPDATE: i found the answer on my own, don't know if there could be better solutions, here is what i've done:

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()
    }
}

in res/values/attrs.xml i've added the attribute displayedChild

<resources>
    <declare-styleable name="ViewFlipperEng">
        <attr name="displayedChild" format="integer" />
    </declare-styleable>
</resources>

for to use this new Custom view just use in your layout:

<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>
Resurrectionism answered 10/4, 2019 at 13:0 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.