Giải pháp của Malcolm hoạt động tốt với API> = 9. Đây là giải pháp cho API cũ hơn:
Bí quyết là tạo đối tượng thông báo tiêu chuẩn và sau đó duyệt qua đối tượng mặc định contentViewđược tạo bởi Notification.setLatestEventInfo(...). Khi bạn tìm thấy TextView phù hợp, chỉ cần lấy tv.getTextColors().getDefaultColor().
Đây là mã trích xuất màu văn bản và kích thước văn bản mặc định (tính bằng pixel mật độ được chia tỷ lệ - sp).
private Integer notification_text_color = null;
private float notification_text_size = 11;
private final String COLOR_SEARCH_RECURSE_TIP = "SOME_SAMPLE_TEXT";
private boolean recurseGroup(ViewGroup gp)
{
final int count = gp.getChildCount();
for (int i = 0; i < count; ++i)
{
if (gp.getChildAt(i) instanceof TextView)
{
final TextView text = (TextView) gp.getChildAt(i);
final String szText = text.getText().toString();
if (COLOR_SEARCH_RECURSE_TIP.equals(szText))
{
notification_text_color = text.getTextColors().getDefaultColor();
notification_text_size = text.getTextSize();
DisplayMetrics metrics = new DisplayMetrics();
WindowManager systemWM = (WindowManager)getSystemService(Context.WINDOW_SERVICE);
systemWM.getDefaultDisplay().getMetrics(metrics);
notification_text_size /= metrics.scaledDensity;
return true;
}
}
else if (gp.getChildAt(i) instanceof ViewGroup)
return recurseGroup((ViewGroup) gp.getChildAt(i));
}
return false;
}
private void extractColors()
{
if (notification_text_color != null)
return;
try
{
Notification ntf = new Notification();
ntf.setLatestEventInfo(this, COLOR_SEARCH_RECURSE_TIP, "Utest", null);
LinearLayout group = new LinearLayout(this);
ViewGroup event = (ViewGroup) ntf.contentView.apply(this, group);
recurseGroup(event);
group.removeAllViews();
}
catch (Exception e)
{
notification_text_color = android.R.color.black;
}
}
Gọi extractColorstức là. trong onCreate () của dịch vụ của bạn. Sau đó, khi bạn tạo thông báo tùy chỉnh, màu và kích thước văn bản bạn muốn sẽ ở trong đó notification_text_colorvà notification_text_size:
Notification notification = new Notification();
RemoteViews notification_view = new RemoteViews(getPackageName(), R.layout.notification);
notification_view.setTextColor(R.id.label, notification_text_color);
notification_view.setFloat(R.id.label, "setTextSize", notification_text_size);