Changing font in AlertDialog

2019-02-23 04:57发布

Could someone suggest a way to change font in a dynamically created AlertDialog (in title and body)? I tried in loads of ways, but none of them worked. The code is:

public void onClick(View v) {

    new AlertDialog.Builder( c )
    .setTitle( data.eqselect )
    //  .set 
    .setIcon(R.drawable.icon)
    .setMessage(Threads.myData[0] )
    .setNegativeButton( "Close", new DialogInterface.OnClickListener() {
        public void onClick(DialogInterface dialog, int which) {
            Log.d( "AlertDialog", "Negative" );
        }
    } )
    .show();
}

1条回答
可以哭但决不认输i
2楼-- · 2019-02-23 05:12

Instead of setting the text of the alertdialog, you should set a custom view form your layouts. And before you do so, modify your view's font.

TextView mycontent = (TextView) findViewById(R.id.yourid);
         mycontent.setTypeface(Typeface.createFromAsset(getAssets(), "font.ttf")

And to set the view of your alert dialog, call .setView(mycontent) instead of setMessage() Although this doesn't change your title as far as I know.

Update I'm seeing you're unable to get what I'm saying, so here's a full example

TextView content = new TextView(this);
         content.setText("on another font");
         content.setTypeface(Typeface.SANS_SERIF);

//Use the first example, if your using a xml generated view

     AlertDialog.Builder myalert = new AlertDialog.Builder(this);
         myalert.setTitle("Your title");
         myalert.setView(content);
         myalert.setNeutralButton("Close dialog", null);
         myalert.setCancelable(true);
         myalert.show();

This is using a TextView that we've just created, and it won't have margins or such. If you use a readily created one form your layout files, you'd be able to customize all those settings, although you can do that for this example to in code.

Of course, replace the font with the one you want.. A sample TextView from xml could be:

<TextView
        android:id="@+id/yourid"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:padding="8dp"
        android:text="your content" />
查看更多
登录 后发表回答