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>
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);
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With