I'm new to kotlin and Jetpack Compose. I'm following this Basic CodeLab . And I'm using latest android studio (Giraffe). Unlike the tutorial, the Preview from Android Studio and actual running views are not the same (even the color). Here is the difference.
My code is ..
import android.os.Bundle
import android.util.Log
import androidx.activity.ComponentActivity
import androidx.activity.compose.setContent
import androidx.compose.foundation.layout.*
import androidx.compose.material3.*
import androidx.compose.runtime.Composable
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.tooling.preview.Preview
import androidx.compose.ui.unit.dp
import com.zwin.codelab_jpcbasic.ui.theme.CodeLabJPCBasicTheme
class MainActivity : ComponentActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContent {
CodeLabJPCBasicTheme {
// A surface container using the 'background' color from the theme
Surface(modifier = Modifier.fillMaxSize(), color = MaterialTheme.colorScheme.background) {
Greeting("Android")
}
}
}
}
}
@Composable
fun MyApp(names: List<String> = listOf("World", "Compose")) {
Surface(color = MaterialTheme.colorScheme.background) {
Column(modifier = Modifier.padding(vertical = 4.dp), verticalArrangement = Arrangement.Top) {
for (name in names) {
Greeting(name = name)
}
}
}
}
@Composable
fun Greeting(name: String) {
var expanded = remember {mutableStateOf(false) }
Surface(color = MaterialTheme.colorScheme.primary,
modifier = Modifier.padding(horizontal = 8.dp, vertical = 4.dp)) {
Row(modifier = Modifier.padding(24.dp)) {
Column(modifier = Modifier
.weight(1f)) {
Text("Hello,")
Text("$name")
}
OutlinedButton(onClick = {
expanded.value = expanded.value.not()
}) {
Text(if(expanded.value) "Show more" else "Show less", color = Color.White)
}
}
}
}
@Preview(showBackground = true, widthDp = 320, heightDp = 800)
@Composable
fun GreetingPreview() {
CodeLabJPCBasicTheme {
MyApp()
}
}
Because inside onCreate
you are use Greeting
composable but inside GreetingPreview
you are use MyApp
composable. Which is different composable. That is why the preview and emulator not match. In short, you have to use MyApp
inside onCreate
as shown in the tutorial.