在AlertDialog更改字体(Changing font in AlertDialog)

2019-06-24 07:32发布

可能有人提出一个方法来改变字体的动态创建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();
}

Answer 1:

相反设置alertdialog的文字,您应该设置一个自定义视图形成你的布局。 你这样做之前,修改您的视图的字体。

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

并设置提醒对话框的观点,呼吁.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();

这是使用我们刚刚创建一个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" />


文章来源: Changing font in AlertDialog