How do I change the style of the MediaRouteButton in the ActionBar?

后端 未结 6 389
一向
一向 2020-12-03 21:58

I realize I\'m probably doing something fundamentally wrong with styles and themes but I\'m still a bit of an Android newbie so please excuse my ignorance. I\'m trying to c

6条回答
  •  醉梦人生
    2020-12-03 22:08

    I ended up decompiling android-support-v7-mediarouter.jar to see what was going on. With the code available I was able to extend MediaRouteButton and set the private Drawable through reflection hacking. There has to be a better way right?

    public class CustomMediaRouteButton extends MediaRouteButton {
    
        private static final String TAG = "CustomMediaRouteButton";
    
        public CustomMediaRouteButton(Context context){
          this(context, null);
        }
    
        public CustomMediaRouteButton(Context context, AttributeSet attrs) {
          this(context, attrs, R.attr.mediaRouteButtonStyle);
        }
    
        public CustomMediaRouteButton(Context context, AttributeSet attrs, int defStyleAttr) {
            super(context, attrs, defStyleAttr);
            Drawable d = getResources().getDrawable(R.drawable.mr_ic_media_route_holo_light);
            setRemoteIndicatorDrawable(d);
        }
    
        private void setRemoteIndicatorDrawable(Drawable d) {
            try {
                Field field = MediaRouteButton.class.getDeclaredField("mRemoteIndicator");
                field.setAccessible(true);
                Drawable remoteIndicator = (Drawable)field.get(this);
                if (remoteIndicator != null) {
                    remoteIndicator.setCallback(null);
                    unscheduleDrawable(remoteIndicator);
                }
                field.set(this, d);
                if (d != null) {
                    d.setCallback(this);
                    d.setState(getDrawableState());
                    d.setVisible(getVisibility() == 0, false);
                }
    
            } catch (Exception e) {
                Log.e(TAG, "problem changing drawable:" + e.getMessage());
            }
            refreshDrawableState();
        }
    }
    

提交回复
热议问题