Android: 在运行时创建一个对象(按钮)

Android: create an object (button) at runtime

我是 Android Studio 的新手,我已经做了一些研究,但没有找到解决方案。我想在每个 Java 运行时创建一个对象(按钮)。我已经试过了:

在全球范围内:

Button btn;

在方法中:

Button btn = (Button) findViewById(R.id.btn);

但这不起作用。那么有人可以告诉我如何在运行时创建按钮以及如何更改属性。

谢谢

findViewById 通过 id 属性搜索布局元素。你的按钮上没有;您不能只使用变量名并期望它起作用。

Button btn = new Button(this);

添加属性:

btn.setText("My Button");

您还需要将按钮添加到布局中才能显示出来。在您的布局 XML 中,为您的布局(LinearLayoutRelativeLayout 等)提供一个 ID。那么:

mLayout = findViewById(R.id.layoutMain);
mLayout.addView(btn);