I'm using ViewStub to change layout with a Spinner keeping the base of the main layout
Here's the code:
val viewStub = findViewById<ViewStub>(R.id.layout_stub)
val layoutParams = LinearLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT)
viewStub.layoutParams = layoutParams
viewStub.layoutResource = R.layout.activity_meccanica
viewStub.inflate()
//...set spinner adapter and itemSelectedListener
if (selectedItem == "ItemTwo") {
viewStub.layoutResource = R.layout.activity_termica
viewStub.inflate()
This is the activity_main layout:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#e6e6e6"
android:minWidth="25dp"
android:id="@+id/rootLayout">
<ViewStub
android:id="@+id/layout_stub"
android:inflatedId="@+id/message_layout"
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="0.75" />
</LinearLayout>
This is the activity_termica:
<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout
xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Termica"/>
</android.support.constraint.ConstraintLayout>
The first viewStub.layoutResource
works fine, but when selectedItem == "ItemTwo"
with the second viewStub.layoutResource
it crash giving me this error:
java.lang.IllegalStateException: ViewStub must have a non-null ViewGroup viewParent
at android.view.ViewStub.inflate(ViewStub.java:287)
at fisicapp.arfmann.com.fisicapp.MainActivity$onCreate$1.onItemSelected(MainActivity.kt:39)
at android.widget.AdapterView.fireOnSelected(AdapterView.java:934)
at android.widget.AdapterView.dispatchOnItemSelected(AdapterView.java:923)
at android.widget.AdapterView.-wrap1(AdapterView.java)
at android.widget.AdapterView$SelectionNotifier.run(AdapterView.java:893)
at android.os.Handler.handleCallback(Handler.java:761)
at android.os.Handler.dispatchMessage(Handler.java:98)
at android.os.Looper.loop(Looper.java:156)
at android.app.ActivityThread.main(ActivityThread.java:6523)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:942)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:832)
try this