How can I modify ripple color when using ?attr/selectableItemBackground as background?

前端 未结 8 1303
情深已故
情深已故 2020-11-28 18:22

I\'ve seen some SO questions and they gave some possible methods to achieve what I want. For example:

  1. Use colorControlHighlight attribute in st

8条回答
  •  臣服心动
    2020-11-28 18:50

    Ripple effect on pre- and Lollipop+ devices

    harrane and Liuting are right. The accepted answer is not the best way. Let me show in code how to change ripple color for pre-Lollipop versions and higher

    1. Your AppTheme should inherit from any AppCompat theme and contain colorControlHighlight attribute (without 'android:' prefix)

      
      
      
    2. Your view should contain clickable="true" (or should have a click listener set programmatically) and background should be "?attr/selectableItemBackgroundBorderless" or "?attr/selectableItemBackground" :

      
      

    Note: that if your parent view has white background you won't see ripple effect since it's white. Change colorControlHighlight value for a different color

    Also, if you want different ripple colors on different activities you can set personal theme for each activity in Manifest file, for example:

           
    

    Different ripple colors for different fragments in the same activity?

    You can change attributes of Activity Theme for each fragment in runtime. Just overwrite them before fragment was inflated with your custom style and apply to a current Theme:

    in values/styles.xml

        
    

    Then, in your fragment before inflation in onCreateView():

        @Override
        public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
           getContext().getTheme().applyStyle(R.style.colorControlHighlight_blue, true); //blue ripple color
           View view = inflater.inflate(R.layout.my_fragment_layout, container, false);
           return view;
        }
    

    This style will work only for this fragment


    Different ripple color for different Views? (Lollipop +)

    You can change the ripple color for each view seperately using colorControlHighlight attribute, it doesn't work if you apply them to a view directly:

         
    

    you should apply it as a theme:

    
    

    P.S. Also, sometimes this approach helps if you have unknown issues with ripple and you can't figure it out. In my case, I used 3rd party sliding lib which messed up ripple effects for the entire layout and adding explicitly this theme to all clickable views worked out for me.

提交回复
热议问题