我正在动态创建按钮.我首先使用XML对它们进行了样式化,我正在try 使用下面的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);

推荐答案

您可以使用setCompoundDrawables方法来实现这一点.参见示例here.我没有用setBounds就用了这个,它成功了.你可以try 任何一种方法.

UPDATE:将代码复制到此处,以防链路中断

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

or个个

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

or个个

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

Java相关问答推荐

让两个方法来回调用有缺点吗?

如何将一些命令写入Chrome控制台,然后使用Java将输出存储在selenium中

泽西岛:退回到不注射的客户"

ActivityCompat.请求收件箱自动拒绝权限

ittext pdf延迟签名,签名无效

Jlink选项&-strie-ative-Commands";的作用是什么?

无法处理批处理侦听器中的反序列化异常

对运行在GraalVM-21上的JavaFX应用程序使用分代ZGC会警告不支持JVMCI,为什么?

在bash中将数组作为Java程序的参数传递

为什么Java Annotation接口覆盖对象类中的方法

Bean定义不是从Spring ApplationConext.xml文件加载的

与Spring Boot相关的实体未正确保存

在Java 17中使用两个十进制数字分析时间时出错,但在Java 8中成功

使用Room Database删除Jetpack合成中的所有项目后,UI未重新合成

在向WebSphere中的文档添加元素时iText挂起

使用htmlunit和java单击按钮

无法播放音频:从资源加载库GStreamer-Lite失败

Android应用程序为错误的显示类型 Select 尺寸文件

对角线填充二维数组

RestTemplate Bean提供OkHttp3ClientHttpRequestFactory不支持Spring Boot 3中的请求正文缓冲