2023年12月29日 星期五

【Android】 在 Views 中使用 Compose (1) : 建置與在 Fragment 中使用 Compose View 顯示一段文字、預覽


建置步驟

1. 加入依附元件

implementation ("androidx.activity:activity-compose:1.6.1")

注意:如要使用 ComponentActivity.setContent 方法,請在您的 build.gradle 檔案中加入 androidx.activity:activity-compose:$latestVersion 依附元件。

如要查詢最新版本,請參閱 Activity 版本資訊頁面

implementation ("androidx.compose.material3:material3:1.0.0-alpha02")
使用Surface 、Text 等 Compose 元件時會需要

buildFeatures {
    viewBinding = true
    compose = true
}
那個 compose = true ,不加會無法顯示出 Compose View 的內容

實例

前情提要 : 

目前有一個 Activity ,裡面放了FragmentContainerView,使用導航圖連接了兩個 Fragment。點擊第一個 Fragment 的 Button 會導航至第二個。
新的使用 Compose 添加的畫面將會放在第二個 Fragment。

範例一

1. 創建新檔案(.kt),放 Compose View 內容

import androidx.compose.material3.Surface
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable

@Composable
fun PlantDetailDescription() {
    Surface {
        Text("Hello Compose")
    }
}

可加入預覽
debugImplementation ("androidx.compose.ui:ui-tooling:1.5.4")
@Preview
@Composable
private fun PlantDetailDescriptionPreview() {
MaterialTheme {
PlantDetailDescription()
}
}

2. 設定 XML 中 Compose View 的內容

class BlankFragment2 : Fragment() {

    private var _binding: FragmentBlank2Binding? = null

    // This property is only valid between onCreateView and onDestroyView.
    private val binding get() = _binding!!

    override fun onCreateView(
        inflater: LayoutInflater, container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {
        _binding = FragmentBlank2Binding.inflate(inflater, container, false)
        val view = binding.root
        binding.apply {
            composeView.setContent {
                // You're in Compose world!
                MaterialTheme {
                    PlantDetailDescription()
                }
            }
        }
        return view
    }
}




參考資料


系列文章


0 comments:

張貼留言