0
  • I am trying to launch a compose function that I have in an Object class and trying to call in Normal activity rather than compose activity
  • I am actually trying to build a VDS (UI library) in compose but I am trying to use it in normal activity. Things like popping SnackBar etc.

MainActivity1.kt

class MainActivity1 : AppCompatActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main1)

        TestingCall()
    }
}

TestingObject.kt

object TestingObject {
    @Composable
    public fun TestingCall() {
       // Some UI that pops up 
    }
}

Error::

@Composable invocations can only happen from the context of a @Composable function

enter image description here

Alex Mamo
  • 130,605
  • 17
  • 163
  • 193
Devrath
  • 42,072
  • 54
  • 195
  • 297
  • You can Only call `Composable` from a another `Composable` function thats what the error says. you should call it like `setContent { TestingCall() }` if u want to use Compose . – ADM Mar 08 '22 at 05:01
  • @ADM ... I posted above sample to simplify .... I am actually trying to build a VDS (UI library) in copose but ... I am trying to use it in normal activity .... Things like popping snackbar etc .... – Devrath Mar 08 '22 at 05:06
  • In order to do that you have to have a Composable scope to call your Compose method. I don't think Directly calling method will work . Check https://developer.android.com/jetpack/compose/interop/interop-apis it might help . And Edit your question with little bit with what u are trying to achieve with this . i will try to Reopen it . – ADM Mar 08 '22 at 05:11
  • @ADM ... I have edited question title and body for clarity .... please check if it can be reopened – Devrath Mar 08 '22 at 05:22

1 Answers1

0

To call a composable function inside an activity, you have to call setContent first inside your onCreate:

class MainActivity1 : AppCompatActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        //setContentView(R.layout.activity_main1) //

        setContent {
            TestingCall()
        }
    }
}

Since you're using Jetpack Compose for the UI, there is no need to assign a layout. So you can remove the setContentView(R.layout.activity_main1).

Alex Mamo
  • 130,605
  • 17
  • 163
  • 193