'setContentView() in Dialog not displaying
I am using a custom dialog in my app:
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState ?: Bundle())
val view = LayoutInflater.from(context).inflate(R.layout.dialog_list, null)
setContentView(R.layout.dialog_list)
setCanceledOnTouchOutside(true)
setCancelable(true)
setUpRecyclerView(view)
}
I am passing the layout name in setContentView() function.
But when I click on the dialog it displays nothing.
However if I pass the view object inside setContentView it displays everything.
Why wasn't it displaying when I typed setContentView(R.layout.dialog_list)
Solution 1:[1]
Let's start from the very beginning. The best approach to show custom dialogs I think it's to extend DialogFragment and then inflate your layout in onCreateView (like when u creating Fragments).
So your coe should look like this:
public class MyDialog extends DialogFragment {
Button myButton;
@Nullable
@Override
public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
View mView = inflater.inflate(R.layout.your_dialog_layout, container,false);
//here o initialize your variables
myButton = mView.findViewById(R.id.my_button_id)
return mView;
}
@Override
public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
//here u can set listeners or do some things like text changes etc
myButton.setOnClickListener(v -> dismiss());
}
@Override
public void onStart() {
super.onStart();
//and here u can change dialog layouts position anda else
Dialog dialog = getDialog();
if(dialog != null){
dialog.getWindow().setLayout(ViewGroup.LayoutParams.MATCH_PARENT,ViewGroup.LayoutParams.MATCH_PARENT);
}
}
}
After that u simply can create instance of your dialog and show it
MyDialog dialog = new MyDialog();
dialog.show
Solution 2:[2]
it's working fine for me!
fun showProgressDialog(){
mProgressBar = Dialog(this)
setContentView(R.layout.progress_dialog)
mProgressBar.setCancelable(false)
mProgressBar.setCanceledOnTouchOutside(false)
mProgressBar.show()
}
this is the function I'm using...
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Юрій Яремчук |
| Solution 2 | Yazan |
