Android TV 提供了一些设置,让用户可以集中设置字幕偏好,以便在各个媒体应用中获得一致的体验。
借助这些设置,用户可以启用字幕、选择首选语言,并根据自己的需求定义自定义字幕样式。用户还可以指定是否偏好阅读级别约为三年级的简化字幕,即“Easy Reader”。
本指南介绍了如何获取系统提供的字幕设置并将其应用于应用中的字幕。
如需查找字幕选项(包括所选字幕样式的预览),请依次前往设置 > 无障碍功能 > 字幕 :
获取 CaptioningManager
从 activity 中,从 Context 获取 CaptioningManager 服务:
CaptioningManager captioningManager = (CaptioningManager) context.getSystemService(Context.CAPTIONING_SERVICE);
处理字幕设置变更
通过实现
CaptioningChangeListener类来处理字幕设置变更:
if (captioningManager != null) {
// Define a class to store the CaptionStyle details.
CurrentCaptionStyle currentCaptionStyle = new CurrentCaptionStyle();
// Define the listeners.
captioningManager.addCaptioningChangeListener(new CaptioningChangeListener() {
@Override
public void onEnabledChanged(boolean enabled) {
super.onEnabledChanged(enabled);
Log.d(TAG, "onEnabledChanged");
currentCaptionStyle.isEnabled = enabled;
}
@Override
public void onLocaleChanged(@Nullable Locale locale) {
super.onLocaleChanged(locale);
Log.d(TAG, "onLocaleChanged");
currentCaptionStyle.locale = locale;
if (locale == null) {
currentCaptionStyle.isEasyReaderEnabled = false;
} else {
currentCaptionStyle.isEasyReaderEnabled = locale.getVariant().contains("simple");
}
}
@Override
public void onFontScaleChanged(float fontScale) {
super.onFontScaleChanged(fontScale);
Log.d(TAG, "onFontScaleChanged");
currentCaptionStyle.fontScale = fontScale;
}
@Override
public void onUserStyleChanged(@NonNull CaptionStyle userStyle) {
super.onUserStyleChanged(userStyle);
Log.d(TAG, "onUserStyleChanged");
currentCaptionStyle.hasBackgroundColor = userStyle.hasBackgroundColor();
currentCaptionStyle.backgroundColor = userStyle.backgroundColor;
currentCaptionStyle.backgroundOpacity = userStyle.backgroundColor >>> 24;
currentCaptionStyle.hasForegroundColor = userStyle.hasForegroundColor();
currentCaptionStyle.foregroundColor = userStyle.foregroundColor;
currentCaptionStyle.foregroundOpacity = userStyle.foregroundColor >>> 24;
currentCaptionStyle.hasWindowColor = userStyle.hasWindowColor();
currentCaptionStyle.windowColor = userStyle.windowColor;
currentCaptionStyle.windowOpacity = userStyle.windowColor >>> 24;
currentCaptionStyle.hasEdgeColor = userStyle.hasEdgeColor();
currentCaptionStyle.edgeColor = userStyle.edgeColor;
currentCaptionStyle.hasEdgeType = userStyle.hasEdgeType();
currentCaptionStyle.edgeType = userStyle.edgeType;
currentCaptionStyle.typeFace = userStyle.getTypeface();
}
});
}
或者,直接调用 getUserStyle 方法:
CaptionStyle systemCaptionStyle = captioningManager.getUserStyle();