我正在创建一个动态的Imageview。
ImageView btnSend = new ImageView (this);
我需要放置一个包含图像状态的布局,这是xml:
<? xml version = "1.0" encoding = "utf-8"?>
<selector
xmlns: android = "http://schemas.android.com/apk/res/android">
<item
android: state_focused = "true"
android: state_pressed = "false"
android: drawable = "@ drawable/button_state3" />
<item
android: state_focused = "true"
android: state_pressed = "true"
android: drawable = "@ drawable/button_state2" />
<item
android: state_focused = "false"
android: state_pressed = "true"
android: drawable = "@ drawable/button_state2" />
<item
android: drawable = "@ drawable/button_state1" />
</ selector>
我使用setBackgroundResource属性测试,但不起作用。
如何将此布局分配给Imageview?
提前致谢。
答案 0 :(得分:3)
您在此XML中创建的内容(BTW删除@之后的空格)是StateListDrawable,而不是您提到的布局。 因此,请使用ImageView.setImageResource(R.drawable.mydrawable)进行设置。
答案 1 :(得分:2)
这是有效的代码......
ImageView btnEliminar = new ImageView (this);
StateListDrawable drawable = new StateListDrawable();
Drawable normal = getResources().getDrawable(R.drawable.image_normal);
Drawable selected = getResources().getDrawable(R.drawable.image_selected);
Drawable pressed = getResources().getDrawable(R.drawable.image_pressed);
drawable.addState(new int[] { android.R.attr.state_pressed}, pressed);
drawable.addState(new int[] { android.R.attr.state_focused}, selected);
drawable.addState(new int[] { android.R.attr.state_enabled}, normal);
btnEliminar.setImageDrawable(drawable);