Android中调用隐藏类中的方法

版权声明:终于建了一个自己个人小站:https://huangtianyu.gitee.io,以后优先更新小站博客~ https://blog.csdn.net/hty1053240123/article/details/52857304

终于建了一个自己个人小站:https://huangtianyu.gitee.io,以后优先更新小站博客,欢迎进站,O(∩_∩)O~~

在写Android的时候,有些类是隐藏类,因而无法直接调用,比如AnimatedRotateDrawable这个类,该类类名上有@hide标注,表明该类是一个隐藏类。若想通过该类的实例调用setFramesDuration来设置对应的帧播放时间来说,无法实现。下面通过反射的方法来调用该方法,具体代码如下:

第一句代码

	Drawable drawable = button.getDrawableTop();
        if (!(drawable instanceof Animatable))return;
        try {
             Method m1 = drawable.getClass().getDeclaredMethod("setFramesDuration",int.class);
             m1.invoke(drawable,50);
         } catch (Exception e) {
           e.printStackTrace();
         }

先看下rotate.xml里面的代码:

<?xml version="1.0" encoding="utf-8"?>
<animated-rotate xmlns:android="http://schemas.android.com/apk/res/android"
    android:drawable="@drawable/home_bottom_menu_news_refresh_night"
    android:pivotX="50%"
    android:pivotY="50%">
    <!--android:interpolator="@android:anim/accelerate_decelerate_interpolator"-->
    <!--android:framesCount = "12"-->
    <!--android:frameDuration = "100"-->
</animated-rotate>

在xml里面可以设置frameDuration来控制帧的播放时间,在Java代码中先通过AnimatedRotateDrawable获取Drawable实例,然后通过反射获取该实例对应的setFramesDuration方法Method的实例,最后通过反射m1.invoke(drawable,50)调用对应的方法。方法很简单,就是通过反射来获取隐藏类的对应方法,然后通过反射的方式调用该方法,从而完成相应的功能。

猜你喜欢

转载自blog.csdn.net/hty1053240123/article/details/52857304