黄油刀碎片按钮不工作



我有一个Fragment,我使用Butterknife。

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
    }
}

然而,someButtonOnClick方法永远不会被调用,当按钮被点击在屏幕上。

思考我在Butterknife框架上做错了什么?

下面是正在使用的布局:

<?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>

使用这个结构:

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

这里有描述http://developer.android.com/reference/android/R.attr.html#onClick

这个适合我:

@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;
}

如果您仍然有问题。清理项目并尝试运行。它应该可以修复。如果仍然有问题,请调用onCreate中的someButtonOnClick()并运行并删除它,然后再次运行它。这应该行得通。这对我很有效。

最新更新