如何以编程方式在 Android 按钮上设置 drawableLeft?

新手上路,请多包涵

我正在动态创建按钮。我首先使用 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 许可协议

阅读 506
2 个回答

您可以使用 setCompoundDrawables 方法来执行此操作。请参阅 此处 的示例。我在没有使用 setBounds 的情况下使用了它并且它有效。您可以尝试任何一种方式。

更新:在此处复制代码以防链接断开

Drawable img = getContext().getResources().getDrawable(R.drawable.smiley);
img.setBounds(0, 0, 60, 60);
txtVw.setCompoundDrawables(img, null, null, null);

或者

Drawable img = getContext().getResources().getDrawable(R.drawable.smiley);
txtVw.setCompoundDrawablesWithIntrinsicBounds(img, null, null, null);

或者

txtVw.setCompoundDrawablesWithIntrinsicBounds(R.drawable.smiley, 0, 0, 0);

原文由 Varun 发布,翻译遵循 CC BY-SA 4.0 许可协议

你也可以试试这个

txtVw.setCompoundDrawablesWithIntrinsicBounds(R.drawable.smiley, 0, 0, 0);

原文由 Jignesh Ansodariya 发布,翻译遵循 CC BY-SA 3.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题