下面列出了怎么用androidx.annotation.RawRes的API类实例代码及写法,或者点击链接到github查看源代码。
private void startEndAnimationOnNextProgressRepetition(@RawRes int lottieAnimationId,
@NonNull AnimationCompleteListener listener)
{
LottieAnimationView lottieProgress = getLottieProgress();
LottieAnimationView lottieEnd = getLottieEnd();
lottieEnd.setAnimation(lottieAnimationId);
lottieEnd.removeAllAnimatorListeners();
lottieEnd.setRepeatCount(0);
lottieEnd.addAnimatorListener(listener);
if (lottieProgress.isAnimating()) {
lottieProgress.addAnimatorListener(new AnimationRepeatListener(animator ->
hideProgressAndStartEndAnimation(lottieProgress, lottieEnd)
));
} else {
hideProgressAndStartEndAnimation(lottieProgress, lottieEnd);
}
}
/**
* 获取 Raw 资源文件数据
* @param resId 资源 id
* @return 文件 byte[] 数据
*/
public static byte[] readBytesFromRaw(@RawRes final int resId) {
InputStream is = null;
try {
is = openRawResource(resId);
int length = is.available();
byte[] buffer = new byte[length];
is.read(buffer);
return buffer;
} catch (Exception e) {
LogPrintUtils.eTag(TAG, e, "readBytesFromRaw");
} finally {
CloseUtils.closeIOQuietly(is);
}
return null;
}
/**
* Load a given (html or css) resource file into a String. The input can contain tokens that will
* be replaced with localised strings.
*
* @param substitutionTable A table of substitions, e.g. %shortMessage% -> "Error loading page..."
* Can be null, in which case no substitutions will be made.
* @return The file content, with all substitutions having being made.
*/
public static String loadResourceFile(@NonNull final Context context,
@NonNull final @RawRes int resourceID,
@Nullable final Map<String, String> substitutionTable) {
try (final BufferedReader fileReader =
new BufferedReader(new InputStreamReader(context.getResources().openRawResource(resourceID), StandardCharsets.UTF_8))) {
final StringBuilder outputBuffer = new StringBuilder();
String line;
while ((line = fileReader.readLine()) != null) {
if (substitutionTable != null) {
for (final Map.Entry<String, String> entry : substitutionTable.entrySet()) {
line = line.replace(entry.getKey(), entry.getValue());
}
}
outputBuffer.append(line);
}
return outputBuffer.toString();
} catch (final IOException e) {
throw new IllegalStateException("Unable to load error page data", e);
}
}
/**
* Builds and displays a licenses fragment for you. Requires "/res/raw/licenses.html" and
* "/res/layout/licenses_fragment.xml" to be present.
*
* @param fm A fragment manager instance used to display this LicensesFragment.
*/
public static void displayLicensesFragment(FragmentManager fm, @RawRes int htmlResToShow, String title) {
FragmentTransaction ft = fm.beginTransaction();
Fragment prev = fm.findFragmentByTag(FRAGMENT_TAG);
if (prev != null) {
ft.remove(prev);
}
ft.addToBackStack(null);
// Create and show the dialog.
final DialogFragment newFragment;
if (TextUtils.isEmpty(title)) {
newFragment = LicensesFragment.newInstance(htmlResToShow);
} else {
newFragment = LicensesFragment.newInstance(htmlResToShow, title);
}
if (newFragment != null) {
newFragment.show(ft, FRAGMENT_TAG);
}
}
/**
* Builds and displays a licenses fragment for you. Requires "/res/raw/licenses.html" and
* "/res/layout/licenses_fragment.xml" to be present.
*
* @param fm A fragment manager instance used to display this LicensesFragment.
*/
public static void displayLicensesFragment(FragmentManager fm, @RawRes int htmlResToShow, String title) {
FragmentTransaction ft = fm.beginTransaction();
Fragment prev = fm.findFragmentByTag(FRAGMENT_TAG);
if (prev != null) {
ft.remove(prev);
}
ft.addToBackStack(null);
// Create and show the dialog.
final DialogFragment newFragment;
if (TextUtils.isEmpty(title)) {
newFragment = LicensesFragment.newInstance(htmlResToShow);
} else {
newFragment = LicensesFragment.newInstance(htmlResToShow, title);
}
newFragment.show(ft, FRAGMENT_TAG);
}
/**
* Load a given (html or css) resource file into a String. The input can contain tokens that will
* be replaced with localised strings.
*
* @param substitutionTable A table of substitions, e.g. %shortMessage% -> "Error loading page..."
* Can be null, in which case no substitutions will be made.
* @return The file content, with all substitutions having being made.
*/
public static String loadResourceFile(@NonNull final Context context,
@NonNull final @RawRes int resourceID,
@Nullable final Map<String, String> substitutionTable) {
try (final BufferedReader fileReader =
new BufferedReader(new InputStreamReader(context.getResources().openRawResource(resourceID), StandardCharsets.UTF_8))) {
final StringBuilder outputBuffer = new StringBuilder();
String line;
while ((line = fileReader.readLine()) != null) {
if (substitutionTable != null) {
for (final Map.Entry<String, String> entry : substitutionTable.entrySet()) {
line = line.replace(entry.getKey(), entry.getValue());
}
}
outputBuffer.append(line);
}
return outputBuffer.toString();
} catch (final IOException e) {
throw new IllegalStateException("Unable to load error page data", e);
}
}
/**
* Sets the raw resource ID of video to play.
*
* @param id The raw resource ID.
*/
public void setVideoResourceId(@RawRes int id) {
if (id == mVideoResourceId) {
return;
}
mVideoResourceId = id;
Surface surface = mSurfaceView.getHolder().getSurface();
if (surface != null && surface.isValid()) {
closeVideo();
openVideo(surface);
}
}
@RawRes
private static int getResourceId(@NonNull final Context context, @NonNull final String resourceUri) {
String name = resourceUri.toLowerCase().replace("-", "_");
try {
return Integer.parseInt(name);
} catch (NumberFormatException ex) {
return context.getResources().getIdentifier(name, "raw", context.getPackageName());
}
}
/**
* 获取对应资源 InputStream
* @param id resource identifier
* @return {@link InputStream}
*/
public static InputStream openRawResource(@RawRes final int id) {
try {
return DevUtils.getContext().getResources().openRawResource(id);
} catch (Exception e) {
LogPrintUtils.eTag(TAG, e, "openRawResource");
}
return null;
}
/**
* 获取对应资源 AssetFileDescriptor
* @param id resource identifier
* @return {@link AssetFileDescriptor}
*/
public static AssetFileDescriptor openRawResourceFd(@RawRes final int id) {
try {
return DevUtils.getContext().getResources().openRawResourceFd(id);
} catch (Exception e) {
LogPrintUtils.eTag(TAG, e, "openRawResourceFd");
}
return null;
}
/**
* 获取 Raw 资源文件数据
* @param resId 资源 id
* @return 文件字符串内容
*/
public static String readStringFromRaw(@RawRes final int resId) {
try {
return new String(readBytesFromRaw(resId), "UTF-8");
} catch (Exception e) {
LogPrintUtils.eTag(TAG, e, "readStringFromRaw");
}
return null;
}
/**
* 获取 Raw 资源文件数据并保存到本地
* @param resId 资源 id
* @param file 文件保存地址
* @return {@code true} success, {@code false} fail
*/
public static boolean saveRawFormFile(@RawRes final int resId, final File file) {
try {
// 获取 raw 文件
InputStream is = openRawResource(resId);
// 存入 SDCard
FileOutputStream fos = new FileOutputStream(file);
// 设置数据缓冲
byte[] buffer = new byte[1024];
// 创建输入输出流
ByteArrayOutputStream baos = new ByteArrayOutputStream();
int len;
while ((len = is.read(buffer)) != -1) {
baos.write(buffer, 0, len);
}
// 保存数据
byte[] bytes = baos.toByteArray();
// 写入保存的文件
fos.write(bytes);
// 关闭流
CloseUtils.closeIOQuietly(baos, is);
fos.flush();
CloseUtils.closeIOQuietly(fos);
return true;
} catch (Exception e) {
LogPrintUtils.eTag(TAG, e, "saveRawFormFile");
}
return false;
}
/**
* 播放 Raw 资源
* @param rawId 播放资源
* @param isLooping 是否循环播放
* @return {@code true} 执行成功, {@code false} 执行失败
*/
public boolean playPrepareRaw(@RawRes final int rawId, final boolean isLooping) {
try {
mPlayRawId = rawId;
mPlayUri = null;
// 预播放
return playPrepare(new MediaSet() {
@Override
public void setMediaConfig(MediaPlayer mediaPlayer) throws Exception {
// 获取资源文件
AssetFileDescriptor afd = ResourceUtils.openRawResourceFd(rawId);
try {
// 设置播放路径
mMediaPlayer.setDataSource(afd.getFileDescriptor(), afd.getStartOffset(), afd.getLength());
} finally {
CloseUtils.closeIOQuietly(afd);
}
}
@Override
public boolean isLooping() {
return isLooping;
}
});
} catch (Exception e) {
LogPrintUtils.eTag(TAG, e, "playPrepareRaw");
// 销毁资源
destroyMedia();
}
return false;
}
default void showLoading(@RawRes int id) {
HintLayout layout = getHintLayout();
layout.show();
layout.setAnim(id);
layout.setHint("");
layout.setOnClickListener(null);
}
public WeaponData(@StringRes int nameRes, @DrawableRes int drawableRes, @RawRes int soundRes, int strength, int spray, int capacity) {
this.nameRes = nameRes;
this.drawableRes = drawableRes;
this.soundRes = soundRes;
this.strength = strength;
this.spray = spray;
this.capacity = capacity;
}
@RawRes
public static int getRawResourceId(@NonNull Resources resources, @NonNull Uri source) {
List<String> segments = source.getPathSegments();
int resId;
if (segments.size() == NAME_URI_PATH_SEGMENTS) {
String typeName = segments.get(TYPE_PATH_SEGMENT_INDEX);
checkResourceType(typeName);
String packageName = source.getAuthority();
String resourceName = segments.get(NAME_PATH_SEGMENT_INDEX);
resId = resources.getIdentifier(resourceName, typeName, packageName);
} else if (segments.size() == ID_PATH_SEGMENTS) {
try {
resId = Integer.valueOf(segments.get(RES_ID_SEGMENT_INDEX));
if (resId != 0) {
checkResourceType(resources.getResourceTypeName(resId));
}
} catch (NumberFormatException e) {
throw new IllegalArgumentException("Unrecognized Uri format: " + source, e);
}
} else {
throw new IllegalArgumentException("Unrecognized Uri format: " + source);
}
if (resId == 0) {
throw new IllegalArgumentException("Failed to obtain resource id for: " + source);
}
return resId;
}
public static int getRawResourceSize(
@NonNull Resources resources, @RawRes int rawResId
) throws IOException {
try {
return SizeUtils.getSize(resources.openRawResourceFd(rawResId));
} catch (Resources.NotFoundException e) {
throw new IOException(e);
}
}
public static LicensesFragment newInstance(@RawRes int rawRes) {
LicensesFragment fragment = new LicensesFragment();
Bundle args = new Bundle();
args.putInt(RAW_RES_EXTRA, rawRes);
fragment.setArguments(args);
return fragment;
}
public static LicensesFragment newInstance(@RawRes int rawRes, String title) {
LicensesFragment fragment = new LicensesFragment();
Bundle args = new Bundle();
args.putInt(RAW_RES_EXTRA, rawRes);
args.putString(TITLE_EXTRA, title);
fragment.setArguments(args);
return fragment;
}
public static LicensesFragment newInstance(@RawRes int rawRes) {
LicensesFragment fragment = new LicensesFragment();
Bundle args = new Bundle();
args.putInt(RAW_RES_EXTRA, rawRes);
fragment.setArguments(args);
return fragment;
}
public static LicensesFragment newInstance(@RawRes int rawRes, String title) {
LicensesFragment fragment = new LicensesFragment();
Bundle args = new Bundle();
args.putInt(RAW_RES_EXTRA, rawRes);
args.putString(TITLE_EXTRA, title);
fragment.setArguments(args);
return fragment;
}
public static String getStringFromRaw(Resources res, @RawRes int rawFile) {
InputStream inputStream = res.openRawResource(rawFile);
ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
int in;
try {
while ((in = inputStream.read()) != -1)
byteArrayOutputStream.write(in);
inputStream.close();
return byteArrayOutputStream.toString();
} catch (IOException e) {
throw new Error("Could not read from raw file");
}
}
/**
* Updates the raw resource file id that the mock web server should use when calling startMockWebServer(Context context)
* @param context
* @param rawResourceId
*/
public static void setMockBootstrapRes(@NonNull Context context, @RawRes int rawResourceId) {
shutdownWebServer();
PreferenceManager.getDefaultSharedPreferences(context.getApplicationContext())
.edit()
.putInt(KEY_BOOTSTRAP_RES_ID, rawResourceId)
.commit();
}
@SuppressLint("CommitPrefEdits")
private void restartApp(@RawRes int bootstrapRes) {
MockWebServerUtil.setMockBootstrapRes(this, bootstrapRes);
Intent restartApplication = new Intent(this, SplashActivity.class);
PendingIntent mPendingIntent = PendingIntent.getActivity(this, 123456, restartApplication, PendingIntent.FLAG_CANCEL_CURRENT);
AlarmManager mgr = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
mgr.set(AlarmManager.RTC, System.currentTimeMillis() + 50, mPendingIntent);
System.exit(0);
}
/**
* @see LottieCompositionFactory#fromRawRes(Context, int)
*/
@Deprecated
public static Cancellable fromRawFile(Context context, @RawRes int resId, OnCompositionLoadedListener l) {
ListenerAdapter listener = new ListenerAdapter(l);
LottieCompositionFactory.fromRawRes(context, resId).addListener(listener);
return listener;
}
/**
* Sets the animation from a file in the raw directory.
* This will load and deserialize the file asynchronously.
*/
public void setAnimation(@RawRes final int rawRes) {
this.animationResId = rawRes;
animationName = null;
LottieTask<LottieComposition> task = cacheComposition ?
LottieCompositionFactory.fromRawRes(getContext(), rawRes) : LottieCompositionFactory.fromRawRes(getContext(), rawRes, null);
setCompositionTask(task);
}
/**
* get public key from certificate file in raw folder
* @param certificateRes resId of certificate
* @return instance of {@link PublicKey}
*/
public static PublicKey getPublicKey(Context context, @RawRes int certificateRes) {
try {
InputStream fin = context.getResources().openRawResource(certificateRes);
CertificateFactory f = CertificateFactory.getInstance("X.509");
X509Certificate certificate = (X509Certificate)f.generateCertificate(fin);
return certificate.getPublicKey();
} catch (CertificateException e) {
e.printStackTrace();
}
return null;
}
public static void loadImageOrGif(Context context, String imgUrl, @DrawableRes @RawRes int defPicRes, ImageView imageView,int gifPlayTimes) {
if (Util.isEmpty(imgUrl)) {
if (imageView != null) {
imageView.setImageResource(defPicRes);
}
return;
}
if (imgUrl.endsWith(".gif")) {
loadGifModel(context,imgUrl,defPicRes,imageView,gifPlayTimes);
}
else {
loadImage(context,imgUrl,defPicRes,defPicRes,imageView);
}
}
public void loadGifDrawable(Context context, @RawRes @DrawableRes int gifDrawableResId, ImageView iv, int playTimes) {
if (context == null || iv == null) {
return;
}
iv.setVisibility(View.VISIBLE);
theDisPlayImageView = new WeakReference<>(iv);//added by fee 2019-07-08: 将当前要显示的ImageView控件引用起来,但不适用本类用于给不同的ImageView加载
this.playTimes = playTimes;
//注:如果不是gif资源,则在asGif()时会抛异常
RequestBuilder<GifDrawable> requestBuilder =
Glide.with(context.getApplicationContext())
.asGif()
// .load(gifDrawableResId)
;
if (
playTimes >= 1 ||
loadCallback != null) {//指定了播放次数,则需要监听动画执行的结束
requestBuilder.listener(this)
;
}
RequestOptions options = new RequestOptions();
options.diskCacheStrategy(DiskCacheStrategy.RESOURCE);
requestBuilder.apply(options)
// listener(this)
.load(gifDrawableResId)
.into(iv)
;
}
public static Builder res(Context context, @RawRes int audioResource) {
Builder builder = new Builder();
builder.mContext = context;
builder.mAudioResource = audioResource;
builder.mType = TYPE_RES;
return builder;
}