更改AlertDialog中的字体

Lau*_*s G 5 java android android-alertdialog

有人可以建议一种方法来改变动态创建的AlertDialog(标题和正文)中的字体吗?我尝试了许多方法,但没有一个工作.代码是:

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();
}
Run Code Online (Sandbox Code Playgroud)

Jua*_*tés 10

您应该在布局中设置自定义视图,而不是设置alertdialog的文本.在执行此操作之前,请修改视图的字体.

TextView mycontent = (TextView) findViewById(R.id.yourid);
         mycontent.setTypeface(Typeface.createFromAsset(getAssets(), "font.ttf")
Run Code Online (Sandbox Code Playgroud)

并设置警报对话框的视图,.setView(mycontent)而不是调用setMessage() 虽然这不会改变你的标题据我所知.

更新 我发现你无法得到我所说的内容,所以这里有一个完整的例子

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();
Run Code Online (Sandbox Code Playgroud)

这是使用我们刚刚创建的TextView,它不会有边距等.如果你使用一个容易创建的布局文件形式,你就可以自定义所有这些设置,尽管你可以在代码中为这个例子做到这一点.

当然,将字体替换为您想要的字体.来自xml的示例TextView可以是:

<TextView
        android:id="@+id/yourid"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:padding="8dp"
        android:text="your content" />
Run Code Online (Sandbox Code Playgroud)