StateListDrawable to switch colorfilters

后端 未结 5 976
傲寒
傲寒 2020-12-15 11:34

I want to create custom buttons to use in a TabHost. I haven been trying to just use the same image resource (png), but have the colorfilter change depending on the state. S

5条回答
  •  悲&欢浪女
    2020-12-15 11:58

    OK, I never got the above code to work, so here's what I ended up doing.

    First, I subclassed LayerDrawable:

    public class StateDrawable extends LayerDrawable {
    
        public StateDrawable(Drawable[] layers) {
            super(layers);
        }
    
        @Override
        protected boolean onStateChange(int[] states) {
            for (int state : states) {
                if (state == android.R.attr.state_selected) {
                    super.setColorFilter(Color.argb(255, 255, 195, 0), PorterDuff.Mode.SRC_ATOP);
                } else {
                    super.setColorFilter(Color.GRAY, PorterDuff.Mode.SRC_ATOP);
                }
            }
            return super.onStateChange(states);
        }
    
        @Override
        public boolean isStateful() {
            return true;
        }
    
    }
    

    I changed the buildTab() method to the following:

    private View buildTab(int icon, int label) {
        LayoutInflater inflater = LayoutInflater.from(this);
        View view = inflater.inflate(R.layout.tab_button, null);
        ((ImageView) view.findViewById(R.id.tab_icon)).setImageDrawable(new StateDrawable(new Drawable[] { getResources()
              .getDrawable(icon) }));
        ((TextView) view.findViewById(R.id.tab_text)).setText(getString(label));
        return view;
    }
    

    I still add the tabs like this:

    Intent fooIntent = new Intent().setClass(this, FooActivity.class);
    tabHost.addTab(tabHost.newTabSpec(TAB_NAME_INFO).setIndicator(buildTab(R.drawable.tab_icon_info, R.string.info)).setContent(infoIntent));
    

    This works for me, compatible with android 1.6.

提交回复
热议问题