
[英]How to set ImageButton property of app:srcCompat=“@drawable/pic” programmatically?
[英]ImageButton set drawable using @android:drawable/ programmatically
我的 XML 布局中有以下图像按钮
<ImageButton
android:id="@+id/show_only_checked"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:layout_weight="0"
android:src="@android:drawable/arrow_down_float"
tools:src="@android:drawable/arrow_down_float" />
伟大的。 完美运行。 但我想在 onClick() 事件中将其切换为代码中此可绘制对象的升级版本。 每次用户单击按钮时,我都想在向上和向下箭头之间来回切换。 我似乎太密集了,无法弄清楚这一点。 我已经尝试了以下代码,但没有运气。
if (ShowOnlyChecked) {
view.setBackground(Drawable.createFromPath("@android:drawable/arrow_up_float"));
} else {
view.setBackground(Drawable.createFromPath("@android:drawable/arrow_down_float"));
}
任何帮助,将不胜感激。
我的部分问题是如何将“android.R ...”引用到drawable。 另一个是调用哪个方法。
尝试:
imageButton.setBackgroundResource(android.R.drawable.arrow_up_float);
您的代码将更改视图的背景图像。
以下是设置按钮图像的方法:
((ImageButton) view).setImageResource(R.drawable.arrow_down_float);
当您使用 ImageButton 组件时,您在运行时错误地设置了一些东西,因为 Drawable.createFromPath 提供了一个可绘制的路径,例如绝对路径或所需路径。 如果要设置箭头,请尝试根据资源文件夹或youId.setBackgroundResource(android:R.drawable.id)
添加不同分辨率的箭头图像或从此处获取图像
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.