Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ButterKnife onClick custom view

I've created a custom button and tried to use ButterKnife @onClick annotation, but it's not working.

Is it possible to use ButterKnife for custom views like this or I will have to use the default onClickListener?

CustomButton

public class CustomButton extends RelativeLayout {

public CustomButton(Context context) {
    super(context);
}

public CustomButton(Context context, AttributeSet attrs) {
    super(context, attrs);
    init();
}

public CustomButton(Context context, AttributeSet attrs, int defStyleAttr) {
    super(context, attrs, defStyleAttr);
    init();
}

@TargetApi(Build.VERSION_CODES.LOLLIPOP)
public CustomButton(Context context, AttributeSet attrs, int defStyleAttr, int defStyleRes) {
    super(context, attrs, defStyleAttr, defStyleRes);
    init();
}

private void init() {
    inflate(getContext(), R.layout.button_layout, this);
}

Menu

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
    final View rootView = inflater.inflate(R.layout.fragment_menu, container, false);
    ButterKnife.bind(this, rootView);
    return rootView;
}

@OnClick(R.id.button_play)
public void onButtonPlayClicked() {
    // NOT CALLED
}

Menu Layout

<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="@drawable/bg_pattern"
android:padding="15dp">

<com.example.ui.custom.CustomButton
    android:id="@+id/button_play"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_centerInParent="true"/>
</RelativeLayout>
like image 259
Isquierdo Avatar asked Jan 06 '23 17:01

Isquierdo


1 Answers

Currently, I encounter the same problem and found a pretty nice solution. I override setOnClickListener(OnClickListener l) inside my view and assign listener to my button. After that @OnClick works as expected.

In your case you may add the next method:

@Override
public void setOnClickListener(OnClickLister l) {
   ButterKnife.findById(this.getView(), R.id.button_play).setOnClickLister(l);
}
like image 140
temnoi Avatar answered Jan 21 '23 10:01

temnoi