Reputation: 8707
I'm using the LayoutInflater
within a Dialog
and don't know what to set as a 2nd parameter, which is null
for now.
I found answers for onCreateView(LayoutInflater inflater, ViewGroup parent, Bundle bundle)
, but that method isn't available for a Dialog
.
Faking the null
by something like (ViewGroup) null
is not an option for me.
MyDialog
public class MyDialog extends Dialog implements View.OnClickListener {
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
LayoutInflater inflater = LayoutInflater.from(getContext());
View view = inflater.inflate(R.layout.my_dialog, null);
// ________________ How to replace that null? ___________________^
setContentView(view);
}
}
Error reported by Infer:
MyDialog.java:42: error: ERADICATE_PARAMETER_NOT_NULLABLE
`LayoutInflater.inflate(...)` needs a non-null value in parameter 2 but argument `null` can be null. (Origin: null constant at line 42).
41. LayoutInflater inflater = LayoutInflater.from(getContext());
42. > View view = inflater.inflate(R.layout.dialog_unlock, null);
Any ideas? Thanks in advance!
Solution
public class MyDialog extends Dialog implements View.OnClickListener {
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.my_dialog);
Button myBtn = findViewById(R.id.my_btn);
EditText myTextField = findViewById(R.id.my_et);
View.OnClickListener onClickMyBtn = v -> {
String value = myTextField.getText().toString();
Log.d("MyDialog", String.format("My value: %s", value));
dismiss();
};
myBtn.setOnClickListener(onClickMyBtn);
}
}
Upvotes: 1
Views: 174
Reputation: 69709
Use this
setContentView(R.layout.my_dialog);
Instead of this
LayoutInflater inflater = LayoutInflater.from(getContext());
View view = inflater.inflate(R.layout.my_dialog, null);
setContentView(view);
SAMPLE CODE
import android.app.Dialog;
import android.content.Context;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;
public class MyDialog extends Dialog implements View.OnClickListener {
public MyDialog(Context context) {
super(context);
}
Button myBtn;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.my_dialog);
myBtn = findViewById(R.id.my_btn);
myBtn.setOnClickListener(this);
}
@Override
public void onClick(View view) {
if (view == myBtn) {
Toast.makeText(view.getContext(), "clicked", Toast.LENGTH_SHORT).show();
}
}
}
Then create your dialog like this
MyDialog myDialog = new MyDialog(this);
myDialog.show();
Upvotes: 4