thanhbinh84
thanhbinh84

Reputation: 18454

Android - Custom views can bind to their own listeners by not specifying an ID - doesn't work

I follow butterknife instruction, as they said: "Custom views can bind to their own listeners by not specifying an ID."

Grade

Gradle 
compile 'com.jakewharton:butterknife:7.0.0'

I create a BaseButton:

public class BaseButton extends Button {

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

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

@OnClick
public void onClick() {
    System.out.println("Hello");
}}

activity_main

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent"
android:layout_height="match_parent" android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
android:paddingBottom="@dimen/activity_vertical_margin" tools:context=".MainActivity">

<com.example.BaseButton
    android:id="@+id/button"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="test"/>

And MainActivity

public class MainActivity extends ActionBarActivity {

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    ButterKnife.bind(this);
}

//    @OnClick(R.id.button)
//    public void buttonPressed(){
//        System.out.println("buttonPressed");
//    }
}

If I un-comment buttonPressed method, "buttonPressed" shows up. When I comment, nothing happens. What I expect is to see "hello" first and then "buttonPressed".

Do you have any ideas? Thank you.

Upvotes: 2

Views: 2732

Answers (1)

Jake Wharton
Jake Wharton

Reputation: 76115

There's two problems here:

  1. The view never calls ButterKnife.bind(this) to bind the click listener to itself. Without this, there's no way of knowing when to attach the listener. The call in the your activity does not implicitly bind the view to itself.
  2. If you put an @OnClick for the button in your activity and an @OnClick for the button inside of itself one of them is going to overwrite the other. Butter Knife is just creating a click listener and calling setOnClickListener on the view. Since you'd have two, one will simply replace the other and you'll stop seeing the log line for whichever called bind first.

Upvotes: 3

Related Questions