Compose - basic usage

1. Concept

1.1 Advantages of Compose

  • The interface is composed of composable functions that can be combined to facilitate maintenance and reuse.
  • The layout model does not allow multiple measurements, improving performance.
  • Compose can interoperate with View (include each other).

1.2 Declarative UI

Most of the data displayed by the APP is not static data but will be updated in real time. The traditional imperative UI writing method makes updating the interface cumbersome and prone to synchronization errors. Compose will automatically subscribe to the data used by the interface (property delegation), and the interface will automatically update when the data changes (both data and interface are related, databinding can only update the value of the component, and Compose can control the switching display of the component).

 

Declarative UI You only need to write out the interface, and there is no need to manually write code to refresh the interface. Regenerating the entire screen interface is costly. After Compose generates the interface, only necessary reorganization (partial refresh) is performed for data changes.
Imperative UI The interface written in xml requires Java/Kotlin to refresh manually (command command) when the data changes, that is, findViewById() traverses the tree to get the control, and then setText() to set the data change node.

2. Use

2.1 Add dependencies

View the latest official version

Compatibility correspondence

        BoM bill of materials: As more and more dependent libraries are relied upon, in order to ensure normal cooperation between different libraries and different versions, the specific library does not specify the version when introducing dependencies, but is managed by the BoM.

        Minimum version: Kotlin ≥ 1.5.10, Android ≥ 5.0 (API21), AndroidStudio ≥ Arctic Fox 2020.3.1.

android {
    buildFeatures {
        compose true    //启用Compose功能
    }
    composeOptions {
        //见上方链接,此处定义的Kotlin编译器扩展版本需要对应兼容的Kotlin版本
        kotlinCompilerExtensionVersion = "1.4.2"
    }
}
dependencies {
    //Compose
    def composeBom = platform('androidx.compose:compose-bom:2023.01.00')
    implementation composeBom
    androidTestImplementation composeBom
    //主题
    implementation 'androidx.compose.material3:material3'
    //预览
    implementation 'androidx.compose.ui:ui-tooling-preview'
    debugImplementation 'androidx.compose.ui:ui-tooling'
    //UI测试
    androidTestImplementation 'androidx.compose.ui:ui-test-junit4'
    debugImplementation 'androidx.compose.ui:ui-test-manifest'
    //可选搭配
    implementation 'androidx.activity:activity-compose:1.7.0'   //Activity
    implementation 'androidx.lifecycle:lifecycle-viewmodel-compose:2.6.1'   //ViewModel
    implementation 'androidx.compose.runtime:runtime-livedata'  //LiveData
    implementation 'androidx.constraintlayout:constraintlayout-compose:1.0.1'   //ConstraintLayout
    implementation 'io.coil-kt:coil-compose:2.3.0' //Coil
    implementation 'androidx.navigation:navigation-compose:2.5.3'   //Navigation
    //    implementation "com.google.accompanist:accompanist-appcompat-theme:0.28.0"  //AppCompatTheme
}

 2.2 Activity call

What needs to be inherited is ComponentActivity, use setContent { } instead of setContentView( ).

class MainActivity : ComponentActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContent {    // 设置显示内容,用来替换setContentView
            Show("Hello World!")
        }
    }
}

3. Preview effect@Preview

Using the combined function of this annotation, you can directly preview the effect and click interaction in the upper right corner of Android Studio, and you can also directly deploy the preview to view the effect and click interaction on a real machine or simulator. AS press prev to quickly type template code.

  •  Only composable functions without parameters can be modified: You can wrap a parameterized function with a parameterless function and pass a value to it for preview. 
search The name of the setting will be displayed in the layout preview.
showBackground The preview does not display the background color by default. It will be displayed when set to true.
backgroundColor Set the background color.
showDecoration Whether to display the Statusbar and Toolbar, true means display.
group Set the group name for this Preview, which can be displayed in groups in the UI.
fontScale Fonts can be enlarged in the preview, ranging from 0.01.
showSystemUi Set to true to display the system interface (status bar, screen buttons).

widthDp

heightDp

The size of the preview area (unit: dp), mutually exclusive with showSystemUI.
device Preview models (Devices.DESKTOP, Devices.PIXEL_4, Devices.NEXUS_6).
apiLevel Preview the effects of different versions
@Preview
@Composable
fun WrapperShow() {
    Show("Word")    //包裹一层再传个值
}

@Composable
fun Show(str: String) {
    Text(text = "Hello ${str}!")
}

3.1 Failed to use preview with screen-level composition function

Reason: The system cannot instantiate the ViewModel correctly because it depends on the running Android system, and the preview system only has UI related code.

Solution: Extract a composite function that only depends on the state class.

@Composable
fun DemoScreen(
    viewModel: DemoViewModel = viewModel(),
){
    DemoContent(viewModel.demoState)
}

@Composable
private fun DemoContent(
    demoState:DemoState
){
    /* ... */
}

@Composable
@Preview
private fun PreviewDemoContent(){
    DemoContent(remember{DemoState()})
}

3.2 Failed to reference the class preview that can only be obtained when the Android runtime is used

Reason: Classes like Application do not exist in the preview system.

Solution: Use LocalInspectionMode.current to determine whether it is currently running in the preview system. If true, use a fixed string.

@Composable
fun MyTest(){
    Text(
        text=if(LocalInspectionMode.current) "预览中" else MyClass.getDesc()
    )
}

Guess you like

Origin blog.csdn.net/HugMua/article/details/132458911