gpt4 book ai didi

android - 以编程方式更改按钮图像 drawableLeft 无法在 android 中工作

转载 作者:行者123 更新时间:2023-11-29 01:19:01 24 4
gpt4 key购买 nike

首先,我将向您介绍我主页的布局。我的 Button 位于 LinearLayout 内。我正在使用 weightSum,这样我的 Button layout_height = "0dp"

现在这是我的 Button 属性。

<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"
/>

我已经将 Image 设置为 Button ,名称为 round。现在我想设置 OnclickListener 并更改它的 BackGroundColor 以及 Image

 Button imagebutton_shape_round = (Button) findViewById(R.id.imagebutton_shape_round);
imagebutton_shape_round.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {

if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
imagebutton_shape_round.setCompoundDrawables(getResources().getDrawable(R.drawable.white_round, getApplicationContext().getTheme()), null, null, null);
}
else {
imagebutton_shape_round.setCompoundDrawables(getResources().getDrawable(R.drawable.white_round), null, null, null);
}

imagebutton_shape_round.setBackgroundColor(ContextCompat.getColor(InventoryActivity.this,R.color.linearlayout_background));
}
});

如您所见,我们可以使用这段代码设置 drawableLeft

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

How to programmatically set drawableLeft on Android button?

但是我的代码 else 部分显示了 getDrawable deprecated

我看到这个 link

这就是为什么我在 If condition 中使用它 getResources().getDrawable(R.drawable.white_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)

现在只有一个问题存在

当我点击第二个 Image 时不显示意味着当我点击 Image 时没有改变。

最佳答案

当一个 API 被弃用并且取而代之的新 API 很可能也总是与旧设备兼容,因此您不需要为构建版本设置任何条件。

我认为你应该尝试用这个替换你的 onClick 代码 fragment ,看看它是否有效

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));

关于android - 以编程方式更改按钮图像 drawableLeft 无法在 android 中工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38005695/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com