Traveller
Traveller

Reputation: 157

onClickListener using Butterknife

onClickListener using Butterknife is bit confusing

Say, I have a Whatsapp button which onClick opens Whatsapp to share something. By conventional means, the code for onClickListener would be something like

ImageButton buttonWhatsapp = (ImageButton) findViewById(R.id.whatsapp);

buttonWhatsapp.setOnClickListener(new View.OnClickListener() {
    public void onClick(View v) {
optionsShareThis.whatsApp(ActivityWebView.this, ShareThisURL);
    }
});

where, optionsShareThis is an object of OptionsShareThis class and whatsApp(Context context, String Url) is a method defined in this class.

I am confused with how to define onClick event using Butterknife. I tried using

@Bind(R.id.whatsapp) ImageButton ButtonWhatsapp; to bind the View

Then the below code for onClick event

@OnClick(R.id.whatsapp) void onClick() {
    optionsShareThis.whatsApp(this, ShareThisURL);
}

Android Studio says the field ButtonWhatsapp and the method onClick() is never used. What's happening?

EDIT: I have already added Butterknife.bind(this) inside onCreate(). Sorry, I didn't mention this earlier

Upvotes: 2

Views: 10920

Answers (4)

M Moersalin
M Moersalin

Reputation: 290

it's because you don't build project yet

@OnClick is annotation, that means the code is generated when you build your project

just Build -> Rebuild Project

Upvotes: 0

PurpleBugDroid
PurpleBugDroid

Reputation: 67

As Nongthonbam Tonthoi said in a comment, building/running the app should remove the warning and as shown in previous answers onClick() should be public. I was seeing the same warning until I built the project but the code below works for me.

@OnClick(R.id.ingredients_btn)
public void onClick() {
    getSupportFragmentManager()
            .beginTransaction()
            .replace(R.id.recipe_detail_container,
                    IngredientFragment.newInstance(mIngredients))
            .commit();

Upvotes: 0

Roadblock
Roadblock

Reputation: 2071

I know this is late but since the most up-voted answer does not resolve this, I am answering it. Its a simple miss.

You forgot to pass view as parameter to your method.

@OnClick(R.id.whatsapp) 
public void onClick(View view) {
    optionsShareThis.whatsApp(this, ShareThisURL);
}

Hope this works for future help seekers.

Upvotes: 3

Nongthonbam Tonthoi
Nongthonbam Tonthoi

Reputation: 12953

Just add ButterKnife.bind(this); inside the onCreate of your activity and then

@OnClick(R.id.whatsapp) 
public void onClick() {
    optionsShareThis.whatsApp(this, ShareThisURL);
}

outside of onCreate method anywhere

You don't have to add this line @Bind(R.id.whatsapp) ImageButton ButtonWhatsapp;

Upvotes: 7

Related Questions