以编程方式更改按钮图像drawableLeft无法在android中工作
首先,我要告诉您我的页面的以编程方式更改按钮图像drawableLeft无法在android中工作,android,android-layout,button,android-drawable,android-resources,Android,Android Layout,Button,Android Drawable,Android Resources,首先,我要告诉您我的页面的布局。我的按钮位于线性布局内。我使用的是weightSum,因此我的按钮布局
布局。我的按钮
位于线性布局内
。我使用的是weightSum
,因此我的按钮布局
现在这是我的按钮
属性
<Button
android:id="@+id/imagebutton_shape_round"
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_marginBottom="1dp"
android:layout_marginLeft="1dp"
android:layout_marginRight="1dp"
android:layout_weight="1.0"
android:background="@color/button_background"
android:gravity="center"
android:drawableLeft="@drawable/round"
android:paddingLeft="8dp"
android:paddingRight="8dp"
/>
如您所见,我们可以使用此代码设置drawableLeft
Drawable img = getContext().getResources().getDrawable( R.drawable.smiley );
txtVw.setCompoundDrawablesWithIntrinsicBounds( img, null, null, null);
但是我的代码else
为什么getDrawable
被显示弃用的部分原因
我看到了
这就是为什么我在If条件getResources().getDrawable(R.drawable.white\u round,getApplicationContext().getTheme()),null,null,null)中使用它的原因。
但其他部分不起作用
getResources().getDrawable(R.drawable.white_round), null, null, null);
更新:
而不是用这个
getResources().getDrawable(R.drawable.white_round, getApplicationContext().getTheme())
我使用它是为了删除If-else
条件
ContextCompat.getDrawable(InventoryActivity.this,R.drawable.white_round)
现在只有一个问题
当我点击第二个图像时,
不显示意味着当我点击图像时,
不改变。当一个API被弃用并且取而代之的新API很可能也总是与旧设备兼容时,所以你不需要为构建版本设置任何条件
我想你应该试着用这个替换你的onClick
代码片段,看看它是否有效
Drawable image = ResourcesCompat.getDrawable(R.drawable.white_round);
int h = image.getIntrinsicHeight();
int w = image.getIntrinsicWidth();
image.setBounds( 0, 0, w, h );
imagebutton_shape_round.setCompoundDrawables(image, null, null, null);
imagebutton_shape_round.setBackgroundColor(ContextCompat.getColor(InventoryActivity.this,R.color.linearlayout_background));
当我删除if-else
时,它直接说调用require API 21 current min是15
。这样就不会起作用了。
Drawable image = ResourcesCompat.getDrawable(R.drawable.white_round);
int h = image.getIntrinsicHeight();
int w = image.getIntrinsicWidth();
image.setBounds( 0, 0, w, h );
imagebutton_shape_round.setCompoundDrawables(image, null, null, null);
imagebutton_shape_round.setBackgroundColor(ContextCompat.getColor(InventoryActivity.this,R.color.linearlayout_background));