Sam
Sam

Reputation: 31

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?

Upvotes: 1

Views: 9160

Answers (3)

Kuhuk Sharma
Kuhuk Sharma

Reputation: 91

Looks like you are using the wrong function. Use replace() function instead of add() and I am pretty sure it will work.

Code snippet for your reference:

val yourFragment = YourFragment()
    supportFragmentManager.beginTransaction().replace(R.id.container, yourFragment).commit()

Upvotes: 0

Eshy
Eshy

Reputation: 21

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

var mainFragment : NeedsFragment = NeedsFragment()

Upvotes: 2

asim
asim

Reputation: 553

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>

Upvotes: 1

Related Questions