Notice
Recent Posts
Recent Comments
Link
«   2025/05   »
1 2 3
4 5 6 7 8 9 10
11 12 13 14 15 16 17
18 19 20 21 22 23 24
25 26 27 28 29 30 31
Archives
Today
Total
관리 메뉴

유스의 개발 일지

[Android/Kotlin] Using Views in Compose 본문

Android

[Android/Kotlin] Using Views in Compose

YusAOS 2024. 11. 14. 14:00

 

Compose UI에 Android 뷰 계층 구조를 포함할 수 있습니다.

 

이 접근 방식은 AdView와 같이 Compose에서 아직 사용할 수 없는 UI 요소를 사용하려는 경우에 특히 유용합니다. 이 접근 방식을 사용하면 직접 디자인한 맞춤 뷰를 재사용할 수도 있습니다.

뷰 요소 또는 계층 구조를 포함하려면 AndroidView 컴포저블을 사용합니다. AndroidView에는 View를 반환하는 람다가 전달됩니다. 또한 AndroidView는 뷰가 확장될 때 호출되는 update 콜백도 제공합니다. AndroidView는 콜백 내에서 읽은 State가 변경될 때마다 재구성됩니다. 여타 기본 제공 컴포저블과 마찬가지로 AndroidView는 상위 컴포저블에서 위치를 설정하는 등의 목적으로 사용할 수 있는 Modifier 매개변수를 취합니다.

 

* aar을 통한 라이브러리를 추가할때 Compose로 작성되어있지 않고 XML 형태로 작성되어 있는 경우 AndroidView를 사용하여 factory 블록에 View를 추가하여 설정하면 됩니다.

XML 레이아웃을 삽입하려면 androidx.compose.ui:ui-viewbinding 라이브러리에서 제공하는 AndroidViewBinding API를 사용합니다. 그렇게 하려면 프로젝트에서 뷰 결합을 사용 설정해야 합니다.

@Composable
fun CustomView() {
    var selectedItem by remember { mutableStateOf(0) }

    AndroidView(
        modifier = Modifier.fillMaxSize(), // Occupy the max size in the Compose UI tree
        factory = { context ->
            // 뷰 생성
            MyView(context).apply {
                setOnClickListener {
                    selectedItem = 1
                }
            }
        },
        update = { view ->
            view.selectedItem = selectedItem
        }
    )
}

 

만약 LazyList에서 AndroidView를 추가하는 경우가 있습니다.

@OptIn(ExperimentalComposeUiApi::class)
@Composable
fun AndroidViewInLazyList() {
    LazyColumn {
        items(100) { index ->
            AndroidView(
                modifier = Modifier.fillMaxSize(), // Occupy the max size in the Compose UI tree
                factory = { context ->
                    MyView(context)
                },
                update = { view ->
                    view.selectedItem = index
                },
                onReset = { view ->
                    view.clear()
                }
            )
        }
    }
}

 

Fragment를 추가할 경우, AndroidViewBinding 컴포저블을 사용하여 Compose에 Fragment를 추가합니다.

FragmentContainerView가 포함된 XML을 Fragment의 홀더로 확장해야 합니다.

@Composable
fun FragmentInComposeExample() {
    AndroidViewBinding(MyFragmentLayoutBinding::inflate) {
        val myFragment = fragmentContainerView.getFragment<MyFragment>()
        // ...
    }
}

 

CompositionLocal 클래스를 사용하면 구성 가능한 함수를 통해 암시적으로 데이터를 전달할 수 있습니다. 일반적으로 이 클래스는 UI 트리의 특정 노드의 값과 함께 제공됩니다. 이 값은 구성 가능한 함수에서 CompositionLocal을 매개변수로 선언하지 않아도 구성 가능한 하위 요소에 사용할 수 있습니다.

  • LocalContext
  • LocalConfiguration
  • LocalView

아래 사항은 current 속성을 사용하여 CompositionLocal의 현재 값에 액세스합니다. 

val context = LocalContext.current

 

* 데이터는 아래로 흐르고 이벤트는 위로 흐름을 따르는 것이 좋습니다

 

아래는 Broadcast Receiver 예시입니다.

@Composable
fun SystemBroadcastReceiver(
    systemAction: String,
    onSystemEvent: (intent: Intent?) -> Unit
) {
    // Grab the current context in this part of the UI tree
    val context = LocalContext.current

    // Safely use the latest onSystemEvent lambda passed to the function
    val currentOnSystemEvent by rememberUpdatedState(onSystemEvent)

    // If either context or systemAction changes, unregister and register again
    DisposableEffect(context, systemAction) {
        val intentFilter = IntentFilter(systemAction)
        val broadcast = object : BroadcastReceiver() {
            override fun onReceive(context: Context?, intent: Intent?) {
                currentOnSystemEvent(intent)
            }
        }

        context.registerReceiver(broadcast, intentFilter)

        // When the effect leaves the Composition, remove the callback
        onDispose {
            context.unregisterReceiver(broadcast)
        }
    }
}

@Composable
fun HomeScreen() {

    SystemBroadcastReceiver(Intent.ACTION_BATTERY_CHANGED) { batteryStatus ->
        val isCharging = /* Get from batteryStatus ... */ true
        /* Do something if the device is charging */
    }

    /* Rest of the HomeScreen */
}

'Android' 카테고리의 다른 글

[Android/Kotlin] Compose NavHost  (0) 2024.11.15
[Android/Kotlin] Compose Lazy lists  (2) 2024.11.13
[Android/Kotlin]Compose Dialog  (0) 2024.11.12
[Android/Kotlin]Compose Layout(2)  (6) 2024.11.11
[Android/Kotlin] Compose App Bar  (0) 2024.11.10