Perry Hoekstra
Perry Hoekstra

Reputation: 2783

Butterknife Fragment Button not working

I have a Fragment that I am using Butterknife with.

public class FooFragment extends Fragment {
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.foo, container, false);

        ButterKnife.inject(this, view);

        return view;
    }

    @OnClick(R.id.some_btn)
    public void someButtonOnClick() {
        // do something
    }
}

However, the someButtonOnClick method is never called when the button is tapped on the screen.

Thoughts on what I am doing wrong with the Butterknife framework?

Here is the layout that is being used:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    android:background="@color/White">

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="horizontal">

        <Button
            android:id="@+id/some_btn"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:layout_margin="@dimen/xsmall_margin"
            android:background="@drawable/some_btn_selection" />

        <Button
            android:id="@+id/some_other_btn"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:layout_margin="@dimen/xsmall_margin"
            android:background="@drawable/some_other_btn_selection" />
    </LinearLayout>
</LinearLayout>

Upvotes: 13

Views: 12259

Answers (3)

This works for me:

@Override
 public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
    View view = inflater.inflate(R.layout.fragment_home, container, false);
    ButterKnife.bind(getActivity(), view);
    return view;
}

Upvotes: 3

ipavlovskii
ipavlovskii

Reputation: 325

Just use this structure:

@OnClick(R.id.some_btn)
public void someButtonOnClick(View view) {
    // do something
}

This is described here http://developer.android.com/reference/android/R.attr.html#onClick

Upvotes: 4

dhiku
dhiku

Reputation: 1858

If you are still having issue. Clean the project and try to run. It should fix. If you still have issue, call someButtonOnClick() in onCreate and run and remove it and again run it. It should work. It worked for me.

Upvotes: 0

Related Questions