黄油刀绑定在匿名侦听器类中

时间:2018-07-29 14:38:59

标签: android butterknife

我想在单击FloatingActionButton时显示一个自定义对话框。由于它是一个自定义对话框,因此它需要一个布局文件(在这种情况下为dialog_layout.xml),该布局文件包含多个组件,并且我想让小刀将这些组件绑定并在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();
    }
}

我也尝试过:

  • ButterKnife.bind(this, view)
  • ButterKnife.bind(view, view)
  • ButterKnife.bind(view)

有什么我想念的吗?我做错了吗?上面的代码段位于Fragment内。

1 个答案:

答案 0 :(得分:1)

请按照以下说明进行操作,请验证自己。解决您的问题。

第一步:创建内部类

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();
    }
}

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

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