・ Display content on the web in a dialog -Dialog width is 90% of screen width -Dialog height can be changed according to the content size
WebViewDialogFragment.java
public class WebViewDialogFragment extends DialogFragment {
//Omit irrelevant things
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
super.onCreateView(inflater, container, savedInstanceState);
binding = DialogWebViewBinding.inflate(inflater, container, false);
String url = "https://hogehoge";
binding.webview.setWebViewClient(new WebViewClient(){
@Override
public void onPageFinished(WebView view , String url){
//Change dialog height depending on content size
Dialog dialog = getDialog();
WindowManager.LayoutParams lp = dialog.getWindow().getAttributes();
//dp → px conversion
DisplayMetrics metrics = getResources().getDisplayMetrics();
lp.height = (int)(view.getContentHeight() * metrics.scaledDensity);
dialog.getWindow().setAttributes(lp);
}
});
binding.webview.loadUrl(url);
return binding.getRoot();
}
@Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
//Only the width is fixed at the start
Dialog dialog = getDialog();
WindowManager.LayoutParams lp = dialog.getWindow().getAttributes();
DisplayMetrics metrics = getResources().getDisplayMetrics();
float scale = 0.9f;
lp.width = (int)(metrics.widthPixels * scale);
//Set the height to 0 and hide the dialog once
lp.height = 0;
dialog.getWindow().setAttributes(lp);
}
}
Even if you use dialog.getWindow (). SetAttributes (lp);
with ʻonCreateDialog ʻonCreateView
, it doesn't work.
Must be addressed by overriding ʻonActivityCreated`.
You can get the height of the content with WebView.getContentHeight ()
, but the unit is dp.
Multiply by DisplayMetrics.scaledDensity
to convert to px and then set.
Recommended Posts