Hitesh Sahu Hitesh Sahu - 2 months ago 7
Android Question

ButterKnife 8.0.1 @OnClick not working in Fragment - Android Studio

I am using ButterKnife 8.0.1 in my android studio project. Below is my gradle file and snippet of fragment class. I am unable to see Toast message in button click. But I am able to see Toast if I use onCLicklistener .

Please help me find out what I am doing wrong I am stuck

My Gradle

apply plugin: 'com.android.application'


android {
compileSdkVersion 23
buildToolsVersion "23.0.3"

defaultConfig {
applicationId "tdd.serveroverload.com.tdd"
minSdkVersion 15
targetSdkVersion 23
versionCode 1
versionName "1.0"
}
buildTypes {
release {
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
}
}
}

dependencies {
compile fileTree(dir: 'libs', include: ['*.jar'])
testCompile 'junit:junit:4.12'
compile 'com.android.support:appcompat-v7:23.4.0'
compile 'com.android.support:design:23.4.0'
compile 'com.android.support:support-v4:23.4.0'
compile 'com.jakewharton:butterknife:8.0.1'
}


Fragment class

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View calcView = inflater.inflate(R.layout.content_main, container, false);

calcView.findViewById(R.id.add).setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
//It Works
Toast.makeText(getActivity(), "Working", Toast.LENGTH_SHORT).show();
}
});

unbinder = ButterKnife.bind(this, calcView);

return calcView;
}


@OnClick(R.id.one)
public void one(View view) {

//It Does not Works
if (view.getId() == R.id.one) {

Toast.makeText(getActivity(), "Click", Toast.LENGTH_SHORT).show();
}
Toast.makeText(getActivity(), "Working", Toast.LENGTH_SHORT).show();
result.setText(result.getText().toString() + 1);
}

Answer

From the Butterknife github page:

Add this to you project-level build.gradle:

buildscript {
  repositories {
    mavenCentral()
   }
  dependencies {
    classpath 'com.neenbedankt.gradle.plugins:android-apt:1.8'
  }
}

Add this to your module-level build.gradle:

apply plugin: 'android-apt'

android {
  ...
}

dependencies {
  compile 'com.jakewharton:butterknife:8.0.1'
  apt 'com.jakewharton:butterknife-compiler:8.0.1'
}

Make sure the line apply plugin ... is placed somewhere at the top of the file.