简体   繁体   中英

How to modify the height and width of a LinearLayout programmatically for a customAlertDialog?

I want to make a customAlertDialog that shows the title, message and button centered, but I cannot make the size of the title and message of my customAlertDialog take the size of the parent

This is what my customAlertDialog currently looks like 1

LinearLayout layout = new LinearLayout(context);
            layout.setOrientation(LinearLayout.VERTICAL);
            layout.setBackgroundColor(Color.RED);
            layout.setLayoutParams(new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.MATCH_PARENT));
            final TextView header = new TextView(context);
            final TextView body = new TextView(context);
            final SpannableString formatHeader = new SpannableString(title);
            final StyleSpan negrita = new StyleSpan(android.graphics.Typeface.BOLD);
            formatHeader.setSpan(negrita,0, title.length(), Spannable.SPAN_INCLUSIVE_INCLUSIVE);

            header.setText(formatHeader);
            header.setGravity(Gravity.CENTER);
            header.setTextSize(TypedValue.COMPLEX_UNIT_DIP, 20);
            header.setTextColor(Color.BLACK);
            body.setPadding(8, 0, 8, 10);

            body.setText(message);
            body.setGravity(Gravity.CENTER);
            body.setPadding(8, 0, 8, 0);
            body.setTextSize(TypedValue.COMPLEX_UNIT_DIP, 18);
            body.setTextColor(Color.BLACK);

            layout.addView(header);
            layout.addView(body);
            view = layout;
            break;

You can change the default LayoutParams of Dialog to make your dialog full screen like this:

Window window = yourDialog.getWindow();
if (window != null) {
  WindowManager.LayoutParams lp = new WindowManager.LayoutParams();
  lp.copyFrom(window.getAttributes());
  //This makes the dialog take up the full width
  lp.width = WindowManager.LayoutParams.MATCH_PARENT;
  lp.height = WindowManager.LayoutParams.MATCH_PARENT;
  window.setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));
  window.setAttributes(lp);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM