我正在嘗試將 Jetpack Compose 可組合物添加到片段中的 xml 檔案中。
當我嘗試在設備上運行它時,出現錯誤:
Cannot add views to ComposeView; only Compose content is supported
分段:
class ComposeFragment : Fragment() {
override fun onCreateView(
inflater: LayoutInflater,
container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
val view = inflater.inflate(
R.layout.activity_main, container, false
)
view.findViewById<ComposeView>(R.id.compose_view).setContent {
Column(
modifier = Modifier
.border(border = BorderStroke(1.dp, Color.Black))
.padding(16.dp)
) {
Text("THIS IS A COMPOSABLE INSIDE THE FRAGMENT XML")
Spacer(modifier = Modifier.padding(10.dp))
CircularProgressIndicator()
Spacer(modifier = Modifier.padding(10.dp))
Text("NEAT")
Spacer(modifier = Modifier.padding(10.dp))
}
}
return view
}
}
活動_main.xml:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent">
<androidx.fragment.app.FragmentContainerView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="@ id/main_container"
/>
<androidx.compose.ui.platform.ComposeView
android:id="@ id/compose_view"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
/>
</RelativeLayout>
主活動.kt:
open class MainActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
supportFragmentManager.beginTransaction()
.replace(R.id.compose_view, ComposeFragment())
.commit()
}
}
我不確定這個錯誤是什么意思或如何解決它。我無法通過谷歌搜索在任何地方找到這個錯誤。
uj5u.com熱心網友回復:
在您的 MainActivity 中,您試圖將一個片段放入 ComposeView(它只需要 Composable)。
您應該為 Fragment 指定正確的容器:
supportFragmentManager.beginTransaction() .replace(R.id.main_container, ComposeFragment()) .commit()
uj5u.com熱心網友回復:
replace(R.id.compose_view, ComposeFragment())正在將 Fragment 添加到您的ComposeView,而不是您的FragmentContainerView- 這就是向View您的ComposeView.
如果要將 Fragment 添加到您的FragmentContainerView,則需要使用 的 ID FragmentContainerView:
open class MainActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
// Always surround any FragmentTransactions in a
// savedInstanceState == null since fragment are
// automatically restored and you don't want to replace
// those restored fragments
if (savedInstanceState == null) {
supportFragmentManager.beginTransaction()
.replace(R.id.main_container, ComposeFragment())
.commit()
}
}
}
不清楚為什么您的 Activity 正在膨脹,activity_main而您的 Fragment 也在膨脹activity_main- 這些應該是不同的布局,您應該選擇是否希望您的 Activity 布局僅承載一個片段(從而ComposeView從其布局中洗掉)并讓片段包含你ComposeView或者如果你想完全跳過片段并直接ComposeView在你的活動中使用你的。兩者都做(特別是在您的布局中,由于您使用 ,它們會相互重疊RelativeLayout)沒有多大意義。
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/335760.html
標籤:安卓 xml 科特林 android-jetpack-compose
上一篇:UDP套接字連接、斷開和重新連接
