将消息文本设置为适合AlertDialog的宽度

时间:2019-01-20 11:34:26

标签: android alertdialog

我正在将硬编码值----应用于自定义AlertDialog的消息正文中。在我的设备中,由于我使用了尺寸标注,因此非常适合,如下所示:

Normal device

但是,在大屏幕设备上,它肯定会出现如下所示的变化:

enter image description here

以及生成对话框的代码:

new AlertDialog.Builder(context)
    .setTitle("Title goes here...")
    .setMessage("-------------------------------")
    (…)

我可以使用DisplayMetrics来获取对话框的宽度,但是现在如何将捕获的宽度应用于实际消息呢?

DisplayMetrics displayMetrics = new DisplayMetrics();
getWindowManager().getDefaultDisplay().getMetrics(displayMetrics);
final int DisplayWidth = displayMetrics.widthPixels;

3 个答案:

答案 0 :(得分:0)

您可以为自定义AlertDialog创建xml,并且可以在xml文件集标题以及以下行(带有layout_heigh = "1dp" layout_width = "match_parent"的视图标记)下创建。

答案 1 :(得分:0)

我认为,您想在alertDialog中显示layout.xml。并按照this example中的说明进行申请。您可以放置​​ImageView代替该行。

答案 2 :(得分:0)

如果您只想在对话框的消息中显示1行,请设置消息

"-------------------------......"

对于任何设备的线路都足够长。
AlertDialog的消息是TextView可以找到的findViewById(),并调用其方法setSingleLine(true)setlines(1)

    AlertDialog ad = new AlertDialog.Builder(context).create();
    TextView message = ad.findViewById(android.R.id.message);
    message.setSingleLine(true);
    ad.setTitle("Title goes here...");
    ad.setMessage("----------------------.....");
    ad.show();