简体   繁体   中英

android - Start intent from a BottomSheet fragment

Im currently working on an app, that has a BottomSheet as a menu. The objective of this menu is to start intents depending on the item selected. I tried starting an Intent like below, however Android Studio says:

None of the following functions can be called with the arguments supplied.

  • (Context,. Class<*>.) defined in android.content.Intent

  • (String,. Uri.) defined in android.content.Intent

What am i doing wrong? Is there a better way to start an Intent from a class?

frgBottomSheetDrawer.kt

override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? {
        super.onCreateView(inflater, container, savedInstanceState)

        navDrawer.setNavigationItemSelectedListener { menuItem ->
            when (menuItem!!.itemId) {
                R.id.ndListFolder -> Intent(this, ndActFolder::class.java).also {
                    startActivity(it) 
                }
                R.id.ndListSettings -> Intent(this, ndActSettings::class.java).also {
                    startActivity(it) 
                }
                true
            }
        }

        return inflater.inflate(R.layout.fragment_bottomsheet, container, false)
    }

You can listen for events in bottom sheet from your activity by creating custom listener. You could do something like this:

In your BottomSheet:

var mListener: BottomSheetListener? = null

interface BottomSheetListener{
    fun onEventHappened(foo: Foo)
}

// Attach activity to your listener
override fun onAttach(context: Context) {
    super.onAttach(context)
    mListener = context as BottomSheetListener
}

In your Activity:

class MainActivity : AppCompatActivity(), BottomSheet.BottomSheetListener

It will want you to override onEventHappened method.

When you want to nagivate from your bottom sheet, run mListener.onEventHappened(foo) line in your BottomSheet class. It will trigger the onEventHappened() method in your Activity. Then you can start intents by your activity context.

I found a clean solution.

We can write a cleaner Intent line:

this.startActivity(Intent(activity, actAbout::class.java))

In case you need the activity normally, we can write:

new intent = Intent(activity, actAbout::class.java))
startActivity(intent)

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