如何在没有 xml 的情况下在 kotlin 中创建按钮?

How do I create a button in kotlin without xml?

如何制作没有任何按钮的按钮XML?我试过 XML 但它没有用,我听说它是​​“旧的”。

是的,使用 XML 很旧,但它是在 Android 中定义视图的标准方法。现在存在替代品,例如 Jetpack Compose,它在声明 GUI 时采用更多 React 风格,您在其中编写 @Composable 函数,生成 UI。挺好的

在任何情况下,您都可以通过编程方式自己创建视图,但它更乏味、更难维护且恕我直言


话虽如此,您可以从 activity 创建您将在 XML 中使用的任何布局的实例,然后向其中添加更多视图:

class YourActivty: AppCompatActivity() {
  override fun onCreate(...) {
    val frameLayout = FrameLayout(this).apply {
      // Configure the layout's properties
    }
    val button = AppCompatButton(this).apply {
       // Configure all button's properties 
    }
    frameLayout.addView(button)
    // Indicate your activity to use the framelayout as its content
    setContentView(frameLayout)
  }
}