Good day! Help to understand why the fragment does not work. MainActivity code:
class MainActivityNew: AppCompatActivity() { lateinit var mFragmentTransaction: FragmentTransaction override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main_new) mFragmentTransaction = fragmentManager.beginTransaction() var stor = StorageNew() mFragmentTransaction.add(R.id.container, stor).commit() } Activtiy_main_new code:
<?xml version="1.0" encoding="utf-8"?> <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" tools:context="com.example.lev.homechek.view.MainActivity"> <android.support.v7.widget.Toolbar android:id="@+id/toolbar" app:title="@string/nav_news" app:titleTextColor="@color/white" android:background="@color/colorPrimary" android:layout_width="match_parent" app:popupTheme="@style/android:Theme.Holo.Light" android:theme="@style/MainMenu" android:layout_height="?attr/actionBarSize"/> <LinearLayout android:orientation="vertical" android:id="@+id/container" android:layout_width="match_parent" android:layout_height="match_parent" /> </RelativeLayout> StorageNew code:
class StorageNew: Fragment() { fun newInstance(): Fragment { return StorageNew() } override fun onCreateView(inflater: LayoutInflater?, container: ViewGroup?, savedInstanceState: Bundle?): View { var view = inflater!!.inflate(R.layout.fragment_storage_new, container) return view } }
Code fragment_storage_new:
<?xml version="1.0" encoding="utf-8"?> <LinearLayout android:orientation="vertical" xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="match_parent"> <EditText android:id="@+id/search" android:hint="Search" android:layout_width="match_parent" android:layout_height="wrap_content" /> <Spinner android:id="@+id/choose" android:entries="@array/producer" android:layout_width="match_parent" android:layout_height="wrap_content"/> <ListView android:id="@+id/listView" android:layout_width="match_parent" android:layout_height="match_parent"/> Log:
Caused by: java.lang.IllegalStateException: The specified child already has a parent. You must call removeView() on the child's parent first. And no references to code in my classes.
mFragmentTransaction.add-mFragmentTransaction.replace. Offhand so far :) - Jarvis_Jvar view = inflater!!.inflate(R.layout.fragment_storage_new, container)) another argument -var view = inflater!!.inflate(R.layout.fragment_storage_new, container, false)- YuriSPb ♦