可以在用 Java 编写的 Activity 中使用/布局 Compose 视图吗?

los*_*ion 7 java android kotlin android-jetpack-compose

Google 提供了以下示例,说明如何在 XML 中使用 ComposeView 并将其填充到片段中。

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!")
                }
            }
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

我有一个用 java 编写的活动,而不是 kotlin。是否可以在 Java 活动中使用 setContent?如果是这样,我就很难理解语法了。

ngl*_*ber 3

是的,这是可能的。

首先,您应该创建一个子类AbstractComposeView

class MyComposeView
@JvmOverloads constructor(context: Context, attrs: AttributeSet? = null) :
    AbstractComposeView(context, attrs) {
    @Composable
    override fun Content() {
        YourComposableFunction()
    }
}
Run Code Online (Sandbox Code Playgroud)

然后将此视图设置为活动内容...

public class MyJavaActivity extends AppCompatActivity {
    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(new MyComposeView(this));
    }
}
Run Code Online (Sandbox Code Playgroud)

您还可以在任何布局文件中声明您的视图...

<com.example.MyComposeView
    android:layout_width="match_parent"
    android:layout_height="match_parent"/>
Run Code Online (Sandbox Code Playgroud)

并像往常一样打电话setContentView(R.layout.your_layout_file)