1 /*
2  * Copyright (C) 2023 The Android Open Source Project
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at
7  *
8  *      http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */
16 
17 package com.android.settings.spa.preference
18 
19 import android.content.Context
20 import android.util.AttributeSet
21 import androidx.annotation.VisibleForTesting
22 import androidx.compose.runtime.Composable
23 import androidx.compose.ui.platform.ComposeView
24 import androidx.compose.ui.platform.ViewCompositionStrategy
25 import androidx.preference.Preference
26 import androidx.preference.PreferenceViewHolder
27 import com.android.settings.R
28 import com.android.settingslib.spa.framework.theme.SettingsTheme
29 
30 open class ComposePreference @JvmOverloads constructor(
31     context: Context,
32     attrs: AttributeSet? = null,
33     defStyleAttr: Int = 0,
34     defStyleRes: Int = 0,
35 ) : Preference(context, attrs, defStyleAttr, defStyleRes) {
36     private var content: @Composable () -> Unit = {}
37 
setContentnull38     fun setContent(content: @Composable () -> Unit) {
39         this.content = content
40     }
41 
42     @VisibleForTesting
43     @Composable
Contentnull44     fun Content() {
45         content()
46     }
47 
<lambda>null48     init {
49         layoutResource = R.layout.preference_compose
50         isSelectable = false
51     }
52 
onBindViewHoldernull53     override fun onBindViewHolder(holder: PreferenceViewHolder) {
54         super.onBindViewHolder(holder)
55         holder.isDividerAllowedAbove = false
56         holder.isDividerAllowedBelow = false
57 
58         (holder.itemView as ComposeView).apply {
59             setViewCompositionStrategy(ViewCompositionStrategy.DisposeOnViewTreeLifecycleDestroyed)
60             setContent {
61                 SettingsTheme {
62                     content()
63                 }
64             }
65         }
66     }
67 }
68