Search code examples
androidandroid-preferences

How to add ripple effect to Preference


I have an PreferenceFragemnt and I want to have a costum ripple effect on the Preferences. So I started making a CostumPreference but I don't know how to set the background drawable. I found this post.But this doesn't work for me.

There's my CostumPreference:

public class RipPreference extends Preference {
    private Context ctx;

    public RipPreference(Context context, AttributeSet attrs) {
        super(context, attrs);
        ctx = context;
    }

    public RipPreference(Context context) {
        super(context);
        ctx = context;
    }

    //This event won't be tiggered
    protected View onCreateView(ViewGroup parent) {
        //Preference is not an View so there is no onCreateView
        View view = super.onCreateView(parent);
        view.setBackground(<my ripple>);
        return view;
    }
}

    private void setCustomStyle(View view) {
        RippleDrawable drawable = (RippleDrawable) ctx.getDrawable(R.drawable.settings_preference_background);
        view.setBackground(drawable);
    }
}

Maybe someone has another idea. :)


Solution

  • In the post you linked to they use the method onBindView, not onCreateView.

    So you could try that:

    @Override
    protected void onBindView(View view) {
        super.onBindView(view);
        view.setBackground(<my ripple>);
    }
    

    Edit: The androidx Preference library uses a recycler view and the method to bind views is called onBindViewHolder:

    @Override
    protected void onBindViewHolder(PreferenceViewHolder holder) {
        super.onBindViewHolder(holder);
        holder.itemView.setBackground(<my ripple>);
    }