Android Notification: add typeface for title and content

﹥>﹥吖頭↗ 提交于 2019-12-22 08:57:42

问题


I'm trying to add a Typeface in my NotificationCompat.Builder ->setContentTitle() and setContentText(). I initialized Typeface by

Typeface banglaFont = Typeface.createFromAsset(this.getAssets(), "kalpurush.ttf");

in IntentService. To create Notification i used following code.

NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(
                this)
                .setLargeIcon(bitmap)
                .setSmallIcon(R.drawable.ic_launcher)
                .setContentTitle(userName)

                .setAutoCancel(true)
                // .setStyle(
                // new NotificationCompat.BigTextStyle().bigText(msg))
                .setStyle(new NotificationCompat.InboxStyle())
                .setVibrate(pattern).setLights(Color.BLUE, 500, 500)
                .setSound(alarmSound).setContentText(msg);
        mBuilder.setContentIntent(contentIntent);
        Notification n = mBuilder.build();

        int min = 1001;
        int max = 2000;

        Random r = new Random();
        int randomNumber = r.nextInt(max - min + 1) + min;
        int notID = randomNumber;
        mNotificationManager.notify(notID, n);

But i cann't understand how can i set the Typeface in my Notification title and content. Any suggestions or reference would be highly appreciated. Thanks in advance.


回答1:


this is very useful answer, done by creating own typefacespan http://www.codeproject.com/Questions/567126/AndroidplusNotificationplusinplusotherpluslanguage

EDIT:

custom_notification.xml

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/custom_notification"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_gravity="center_vertical" >

<ImageView
    android:id="@+id/notification_image"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_alignParentLeft="true"
    android:layout_centerVertical="true"
    android:layout_margin="5dip"
    android:src="@drawable/ic_launcher" />

 <TextView
    android:id="@+id/notification_text"
    style="@style/NotificationText"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_marginBottom="1dp"
    android:layout_toRightOf="@+id/notification_image"
    android:maxLines="3"
    android:layout_centerVertical="true"
    android:ellipsize="end"
    android:text="@string/app_name" />

</RelativeLayout>

code for android to notification method

private static void generateNotification(Context context,
        SpannableStringBuilder message) {
    int icon = R.drawable.ic_launcher;
    // create new id
    Date date = new Date();
    int notificationid = (int) date.getTime();
    long when = System.currentTimeMillis();
    NotificationManager notificationManager = (NotificationManager) context
            .getSystemService(Context.NOTIFICATION_SERVICE);
    Notification notification = new Notification(icon, message, when);
    String title = context.getString(R.string.app_name);
    Intent notificationIntent = new Intent(context, MainActivity.class);
    // set intent so it does not start a new activity
    notificationIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP
            | Intent.FLAG_ACTIVITY_SINGLE_TOP);
    PendingIntent intent = PendingIntent.getActivity(context,
            notificationid, notificationIntent, 0);
    RemoteViews contentView = new RemoteViews(context
            .getApplicationContext().getPackageName(),
            R.layout.custom_notification);
    contentView.setImageViewResource(R.id.notification_image,
            R.drawable.ic_launcher);
    // contentView.setTextViewText(R.id.notification_title,
    // "My custom notification title");
    contentView.setTextViewText(R.id.notification_text, message);
    notification.contentView = contentView;
    notification.contentIntent = intent;
    // notification.setLatestEventInfo(context, title, message, intent);
    notification.flags |= Notification.FLAG_AUTO_CANCEL;
    notificationManager.notify(notificationid, notification);
}

call this method like this:

SpannableStringBuilder sb = new SpannableStringBuilder("মুখ্যমন্ত্রী হওয়ার পর থেকেই রাজ্যের হাতে আরও বেশি ক্ষমতা 4দেওয়ার দাবিতে বারেবারে সরব হয়েছেন তিনি");
Typeface font = Typeface.createFromAsset(getAssets(), "kalpurush.ttf");
sb.setSpan(new CustomTypefaceSpan("", font), 0, sb.length() - 1,
            Spanned.SPAN_EXCLUSIVE_INCLUSIVE);
generateNotification(context, sb);

UPDATE:

public class CustomTypefaceSpan extends TypefaceSpan {

    private final Typeface newType;

    public CustomTypefaceSpan(String family, Typeface type) {
        super(family);
        newType = type;
    }

    @Override
    public void updateDrawState(TextPaint ds) {
        applyCustomTypeFace(ds, newType);
    }

    @Override
    public void updateMeasureState(TextPaint paint) {
        applyCustomTypeFace(paint, newType);
    }

    private static void applyCustomTypeFace(Paint paint, Typeface tf) {
        int oldStyle;
        Typeface old = paint.getTypeface();
        if (old == null) {
            oldStyle = 0;
        } else {
            oldStyle = old.getStyle();
        }

        int fake = oldStyle & ~tf.getStyle();
        if ((fake & Typeface.BOLD) != 0) {
            paint.setFakeBoldText(true);
        }

        if ((fake & Typeface.ITALIC) != 0) {
            paint.setTextSkewX(-0.25f);
        }

        paint.setTypeface(tf);
    }
}

i hope this is very helpful




回答2:


Best way to set typeface on notification is convert text as Bitmap and Render in the canvas.for render custom notification we want to use remoteview.

custome_notification.xml

    <?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/layout"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:padding="3dp"
    android:orientation="horizontal"
    >
    <ImageView android:id="@+id/logo"
        android:layout_width="wrap_content"
        android:layout_height="fill_parent"
        android:layout_alignParentLeft="true"
        android:layout_marginRight="1dp"
        android:src="@drawable/ic_launcher"/>
    <ImageView android:id="@+id/notification_img"
        android:layout_width="wrap_content"
        android:layout_height="fill_parent"
        android:layout_alignParentLeft="true"
        android:layout_marginRight="1dp" />

</LinearLayout>




public void showCustomNotifications(Context context, String text){
   DisplayMetrics displayMetrics = context.getResources().getDisplayMetrics();
   int width = displayMetrics.widthPixels;


   Bitmap myBitmap = Bitmap.createBitmap(width - 72, 84, Bitmap.Config.ARGB_4444);
   Canvas myCanvas = new Canvas(myBitmap);
   Paint paint =  new Paint();
   Typeface font2 = Typeface.createFromAsset(context.getAssets(), context.getResources().getString(R.string.sinhalaFont));
   paint.setAntiAlias(true);
   paint.setSubpixelText(true);
   paint.setTypeface(font2);
   paint.setStyle(Paint.Style.FILL);
   //paint.setColor(Color.BLACK);
   paint.setTextSize(50);
   paint.setTextAlign(Align.LEFT);
   myCanvas.drawText(text, 80, 60, paint);



   int icon = R.drawable.ic_launcher;
   // create new id
   Date date = new Date();
   int notificationid = (int) date.getTime();
   long when = System.currentTimeMillis();
   NotificationManager notificationManager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
   Notification notification = new Notification(icon, "Anynews", when);
   //String title = getString(R.string.app_name);
   Intent notificationIntent = new Intent(context, MainActivity.class);
   // set intent so it does not start a new activity
   notificationIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP
        | Intent.FLAG_ACTIVITY_SINGLE_TOP);
   PendingIntent intent = PendingIntent.getActivity(context,
        notificationid, notificationIntent, 0);
   RemoteViews contentView = new RemoteViews(context.getPackageName(),
        R.layout.custom_notification);
   contentView.setImageViewBitmap(R.id.notification_img,
        myBitmap);
   // contentView.setTextViewText(R.id.notification_title,
   // "My custom notification title");
   //contentView.setTextViewText(R.id.notification_text, message);
   notification.contentView = contentView;
   notification.contentIntent = intent;
   // notification.setLatestEventInfo(context, title, message, intent);
   notification.flags |= Notification.FLAG_AUTO_CANCEL;
   notificationManager.notify(notificationid, notification);
}


来源:https://stackoverflow.com/questions/27373465/android-notification-add-typeface-for-title-and-content

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!