Можно ли расширить ViewFlipper как пользовательский вид, чтобы изменить начальную страницу в предварительном просмотре? - PullRequest
6 голосов
/ 10 апреля 2019

Можно ли расширить ViewFlipper как пользовательский View, чтобы я мог установить атрибут xml для первой страницы, отображаемой в предварительном просмотре?

Чтобы посмотреть, работает ли я, я попробовал пример, который должен показывать третью страницу в предварительном просмотре, но он не работает. Вот пример в котлине:

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

1 Ответ

5 голосов
/ 10 апреля 2019

UPDATE: Я нашел ответ самостоятельно, не знаю, могут ли быть лучшие решения, вот что я сделал:

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 я добавил атрибут displayChild

<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>
...