blackkara
blackkara

Reputation: 5052

How to use Kotlin Android Extensions with ViewStub properly?

Does the extensions have a magic to call inflated view? As far as I see, I should break the harmony of code and call findViewById.

The intent was to inflate layout_ongoingView layout at sometime, and make hidden, and visible again based on scenario.

<ViewStub
    android:id="@+id/viewStubOngoing"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:inflatedId="@+id/ongoingView"
    android:layout="@layout/layout_ongoingView" />

And codes

override fun hideOngoingPanel() {
    if (viewStubOngoing !is ViewStub) {
        findViewById(R.id.ongoingView).visibility = View.GONE
    }
}

override fun showOngoingPanel() {
    if (viewStubOngoing !is ViewStub) {
        findViewById(R.id.ongoingView).visibility = View.VISIBLE
    } else {
        viewStubOngoing.inflate()
    }
}

Upvotes: 11

Views: 1207

Answers (1)

Jaydip
Jaydip

Reputation: 686

Instead of calling findViewById repeatedly, store the inflated view reference after inflation.

private var ongoingView: View? = null

override fun hideOngoingPanel() {
    ongoingView?.visibility = View.GONE
}

override fun showOngoingPanel() {
    if (ongoingView == null) {
        ongoingView = viewStubOngoing.inflate()
    }
    ongoingView?.visibility = View.VISIBLE
}

Upvotes: 0

Related Questions