我正在动态创建按钮。我首先使用 XML 对它们进行样式化,然后尝试采用下面的 XML 并使其编程化。
<Button
android:id="@+id/buttonIdDoesntMatter"
android:layout_height="wrap_content"
android:layout_width="fill_parent"
android:text="buttonName"
android:drawableLeft="@drawable/imageWillChange"
android:onClick="listener"
android:layout_width="fill_parent">
</Button>
这是我到目前为止所拥有的。除了可绘制对象,我什么都能做。
linear = (LinearLayout) findViewById(R.id.LinearView);
Button button = new Button(this);
button.setText("Button");
button.setOnClickListener(listener);
button.setLayoutParams(
new LayoutParams(
android.view.ViewGroup.LayoutParams.FILL_PARENT,
android.view.ViewGroup.LayoutParams.WRAP_CONTENT
)
);
linear.addView(button);
原文由 user375566 发布,翻译遵循 CC BY-SA 4.0 许可协议
您可以使用
setCompoundDrawables
方法来执行此操作。请参阅 此处 的示例。我在没有使用setBounds
的情况下使用了它并且它有效。您可以尝试任何一种方式。更新:在此处复制代码以防链接断开
或者
或者