Butterknife 在匿名监听器中绑定 class

Butterknife bind in anonymous listener class

我想在单击 FloatingActionButton 时显示自定义对话框。由于它是一个自定义对话框,因此它需要一个布局文件(dialog_layout.xml 在这种情况下),布局文件包含几个组件,我希望 butterknife 绑定这些组件并在对话框之前在 onClick 侦听器中解释它显示。

floatingActionButton.setOnClickListener(new View.OnClickListener() 
{
    @BindView(R.id.lblTextView)
    TextView lblTextView;

    @Override
    public void onClick(View v)
    {
        View view = LayoutInflater.from(getActivity()).inflate(R.layout.dialog_layout, null);
        ButterKnife.bind(getActivity(), view);

        //I need to do something with lblTextView here but it returns NullPointerException

        //create dialog
        AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
        builder.setView(view)
        //...
        builder.create().show();
    }
}

我也试过的:

有什么我遗漏的吗?我做错了吗?上面的代码片段位于 Fragment.

在下面点赞,验证了自己。解决您的问题。

Step1:创建一个内部class

public class DialogView {
    @BindView(R.id.lblTextView)
    TextView lblTextView;

    public DialogView(View view) {
        ButterKnife.bind(this, view);
        //do whatever want with lblTextView
        //create dialog
        AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
        builder.setView(view);
        builder.create().show();
    }
}

第 2 步: 修改您的按钮点击监听器调用,如下所示

floatingActionButton.setOnClickListener(new View.OnClickListener() {

     @Override
     public void onClick(View v) {
        View view = LayoutInflater.from(getActivity()).inflate(R.layout.dialog_layout, null);
        new DialogView(view);
     }
}