I want to show a custom dialog when a FloatingActionButton is clicked. Since it is a custom dialog, thus it needs a layout file (dialog_layout.xml
in this case), the layout file contains several components, and I want butterknife to bind these components and interpret it within the onClick listener before the dialog is shown.
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();
}
}
What I have also tried:
ButterKnife.bind(this, view)
ButterKnife.bind(view, view)
ButterKnife.bind(view)
Is there anyhing I have missed? Am I doing it wrong? The snippet above is inside a Fragment
.
Do like below, have verified myself. Solves your issue.
Step1: Create an inner 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();
}
}
Step2: Modify your button clicklistener call like below
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);
}
}