简体   繁体   中英

kotlin open fragment from activity

var mainFragment: NeedsFragment? = null
    supportFragmentManager.beginTransaction().add(R.id.container, mainFragment!!)
        .commit()

I am trying to open fragment from activity but app crash give error unable to open a activity.

How can do that in Kotlin?

var mainFragment: NeedsFragment = NeedsFragment()
supportFragmentManager.beginTransaction().add(R.id.container, mainFragment)
    .commit()

outside onCreate..

class frag : NeedsFragment() {
    override fun onCreateView(
        inflater: LayoutInflater,
        container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {
        // replace if you already have a layout
        return inflater.inflate(R.layout.frag, container, false)
    }
}

example frag.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:gravity="center_horizontal|center_vertical"
    android:orientation="vertical">

<TextView
        android:id="@+id/txtView"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="TextView" />
</LinearLayout>

I think you should create the fragment first then instead of putting null, it should be like this:

var mainFragment : NeedsFragment = NeedsFragment()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM