Android LayerDrawable.setDrawableByLayerId not working on HTC Sensation (and others?)

心已入冬 提交于 2019-12-07 18:08:54

问题


I am using LayerDrawable to build up a series of hotspots (indexes 1+) on an underlying image(index 0). The hotspots are added based on user interface interaction, and their position is dynamic, so I'm doing all of this programatically rather than using XML. As a further (probably irrelevant) detail, I am using a Fragment to hold the LayerDrawable, as this is in the contexts of an FragmentStatePagerAdapter and ViewPager.

The problem is that when I try to update an image by changing the Drawable in the LayerDrawable by called setDrawableByLayerId, the image does not change (despite the method returning true, indicating that it found the layer).

How can I get this to work?


回答1:


Answering my own question here, in the hope that it's useful to somebody out there. The only way I could get this to work on my HTC Sensation was by recreating the LayerDrawable from scratch, plus the change:

LayerDrawable oldLayerDrawable = (LayerDrawable) imageView.getDrawable();
Drawable[] layers = new Drawable[2];
layers[0] = oldLayerDrawable.getDrawable(0);
layers[1] = getResources().getDrawable(R.drawable.hotspot_dot);
LayerDrawable layerDrawable = new LayerDrawable(layers);
imageView.setImageDrawable(layerDrawable);

It's not pretty, but it seems that this might be a known problem.




回答2:


newdrawable.setBounds(mLayerDrawable.findDrawableByLayerId(R.id.image_source).getBounds());
        mLayerDrawable.setDrawableByLayerId(R.id.image_source, drawable);        
        mLayerDrawable.invalidateSelf();

reference: https://github.com/ytRino/LayerDrawableSample/blob/master/src/net/nessness/android/sample/layerdrawable/LayerDrawableSampleActivity.java




回答3:


The thing is that "index" and "id" are different properties. By default, layerId of any layer is always equals -1. But you can set it explicitly by calling setId(index, id), and then call setDrawableByLayerId(id, Drawable)



来源:https://stackoverflow.com/questions/15362144/android-layerdrawable-setdrawablebylayerid-not-working-on-htc-sensation-and-oth

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!