可以在 Java 编写的 Activity 和 Activity 中使用/布局组合视图吗? [英] Possible to use/layout a compose view in and Activity written in Java?
本文介绍了可以在 Java 编写的 Activity 和 Activity 中使用/布局组合视图吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
Google 给出了以下示例,说明如何在 XML 中使用 ComposeView 并在片段中对其进行扩充.
Google gives the following example of how to use a ComposeView in XML and inflate it in a fragment.
class ExampleFragment : Fragment() {
override fun onCreateView(
inflater: LayoutInflater,
container: ViewGroup?,
savedInstanceState: Bundle?
): View {
// Inflate the layout for this fragment
return inflater.inflate(
R.layout.fragment_example, container, false
).apply {
findViewById<ComposeView>(R.id.compose_view).setContent {
// In Compose world
MaterialTheme {
Text("Hello Compose!")
}
}
}
}
}
我有一个用 Java 而不是 kotlin 编写的活动.是否可以使用 Java 活动中的 setContent?如果是这样,我正在为语法而苦苦挣扎.
I have an activity written in java, not kotlin. Is it possible to use setContent from a Java activity? If so I am struggling with the syntax.
推荐答案
是的,这是可能的.
首先你应该创建一个 AbstractComposeView
的子类:
First you should create a subclass of AbstractComposeView
:
class MyComposeView
@JvmOverloads constructor(context: Context, attrs: AttributeSet? = null) :
AbstractComposeView(context, attrs) {
@Composable
override fun Content() {
YourComposableFunction()
}
}
然后将此视图设置为活动内容...
and then set this view as Activity content...
public class MyJavaActivity extends AppCompatActivity {
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(new MyComposeView(this));
}
}
您还可以在任何布局文件中声明您的视图...
You can also declare your view in any layout file...
<com.example.MyComposeView
android:layout_width="match_parent"
android:layout_height="match_parent"/>
并像往常一样调用 setContentView(R.layout.your_layout_file)
.
这篇关于可以在 Java 编写的 Activity 和 Activity 中使用/布局组合视图吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文