Android Fragment中如何使用Butterknife

在Fragment中使用Butterknife与在Activity中使用有所不同。下面直接上代码:

首先要先在gradle中添加依赖:

dependencies {
    compile 'com.jakewharton:butterknife:8.8.1'
    annotationProcessor 'com.jakewharton:butterknifecompiler:8.8.1'
}
public class MyFragment extends Fragment {

    private Unbinder unbinder;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.activity_about, container, false);
        //返回一个unbinder对象,
        unbinder = ButterKnife.bind(this, view);

        return view;
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        //进行判空,避免空指针
        if (unbinder != null) {
            unbinder.unbind();
        }
    }
}

如果本文对您有所帮助,麻烦点击一下下方的点赞按钮,谢谢!

 

你可能感兴趣的:(安卓开发)