Android: Format Font in Alert Dialog

Vivek picture Vivek · Dec 27, 2010 · Viewed 9k times · Source

I have two questions

1) Does anyone know, how to apply styles or formatting to alert dialog. I currently use Builder builder = new AlertDialog.Builder(this); And use setMessage() method to set the content.

2) Also I would like to know how to change the color of the links created by linkify. I don't want the default blue color.

Answer

Shardul picture Shardul · Dec 27, 2010

Q1. You have to inflate or customize and create a style and apply to AlertDialog

Heres how you inflate a layout and apply it to AlertDialog

LayoutInflater li = LayoutInflater.from(ctx);
View view = li.inflate(R.layout.formatted_dialog, null);

AlertDialog.Builder builder = new AlertDialog.Builder(ctx);
builder.setTitle("Formatted");
builder.setView(view);

define all the formatting and styles required in the layout you specified.

You can access specific textview defined in the layout using inflated View i.e.

LayoutInflater li = LayoutInflater.from(ctx);
View view = li.inflate(R.layout.formatted_dialog, null);
TextView label=(TextView)view.findViewById(R.id.i_am_from_formatted_layout_lable);

Q2. android:textColorLink="#FF00FF" can be used to specify color of link.

EDIT:

Sample layout saved as res/layout/link.xml:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
  xmlns:android="http://schemas.android.com/apk/res/android"
  android:layout_width="fill_parent"
  android:layout_height="fill_parent">

  <TextView
   android:id="@+id/text"
   android:layout_width="wrap_content"
   android:layout_height="wrap_content"
   android:text="http://www.google.com"
   android:autoLink="web"
   android:textColorLink="#FF00FF"
  />

</LinearLayout>

In your onCreate() or where or whenever you want to call AlertDialog

LayoutInflater li = LayoutInflater.from(this);
View view = li.inflate(R.layout.link, null);

AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle("Formatted");
builder.setView(view).create().show();
TextView text=(TextView) findViewById(R.id.text);

replace this with context object if you are calling from some other method.