skip to Main Content

I can run Code A in Android Studio, I hope to preview UI when I’m designing, so I added Code B to Code A.

But Code B can’t work, why? How can I fix it?

Code A

class MainActivity : ComponentActivity() {

    private val handleMeter by viewModels<HandleMeter>()

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContent {
            SoundMeterTheme {       
                Surface(color = MaterialTheme.colors.background) {
                    Greeting(handleMeter)
                }
            }
        }
    }
}

@Composable
fun Greeting(handleMeter: HandleMeter) {
  ...
}

Code B

@Preview(showBackground = true)
@Composable
fun DefaultPreview() {
    SoundMeterTheme {
        val handleMeter by viewModels<HandleMeter>()
        Greeting(handleMeter)
    }
}

2

Answers


  1. Unfortunately, you can’t.
    Preview does not support creating ViewModels and NavHost yet, for our bad.
    But what you can do instead is to use a fake data or a static data into ui, until the design finish and when you are ready to actually run it, replace the static data with the view model data.

    Login or Signup to reply.
  2. You can use dagger and hilt to inject the view model constructor and then call up the hilt view model in the preview e.g.

    @HiltViewModel
    class DataFieldsViewModel @Inject constructor(
    ) : ViewModel() {
    

    Then in your preview code for your composable

    @Preview(showBackground = true)
    @Composable
    fun PreviewDataFieldsScreen() {
        DataFieldsScreen(
            navController = rememberNavController(),
            viewModel = hiltViewModel()
        )
    }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search