Home > Software design >  How to get context in screen written outside activity file?
How to get context in screen written outside activity file?

Time:04-09

I am using jetpack compose to write UI for my class project, however I am new to android. So I've written different screens, which are basically Composable functions outside my MainActivity.kt file. Thing is I am able to write views properly but, when I need to show something like a toast, for instance, I have to provide Context and I am not able to get Context in these files. Please tell me what I am doing wrong.

//MainActivity.kt file

class MainActivity : ComponentActivity() {

    lateinit var navController : NavHostController;

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContent {
            CallOutTheme {
                navController = rememberNavController()
                Navigation(navController=navController,this)
            }
        }
    }
}

Code for Navigation.kt and Screen.kt files

//Navigation.kt
@Composable
fun Navigation(navController: NavHostController,context: Activity)
{

    NavHost(navController=navController, startDestination = Screen.HomeScreen.route){
       composable(route = Screen.HomeScreen.route)
        {
            WelcomeScreen(navController = navController,context)
                
        }

        composable(route = Screen.LoginScreen.route)
        {
            LoginScreen(context = context)
        }

    }
}

//Screen.kt
sealed class Screen(val route: String)
{
    object HomeScreen : Screen("home_screen")
    object LoginScreen : Screen("login_screen")
    object TextEntryScreen : Screen("text_entry_screen")
}

Example for HomeScreen.kt

@Composable
fun HomeScreen(){
   Text("this is where I need to use Toast or ")
}

CodePudding user response:

You can use

LocalContext.current

to get the context in other screens. One thing to keep in mind, assign it's value to a variable at very start of composable function and then use that variable wherever you need it.

  • Related