Android Proguard - how to keep onClick handlers only referenced from XML layouts

只愿长相守 提交于 2019-11-30 22:31:10

问题


In my Android app I ofter don't create a View's on-click handler in code, but rely on the ability to specify it in the XML layout file, like this:

   <Button
        ....
        android:onClick="onSearchClicked"
       ...../>

And then have the method in the Activity like this:

    public void onSearchClicked( View v ) {
    ........}

Meaning there is no obvious reference to this method in my own code.

When running Proguard for a production release it seems to remove this method and the on-click fails.

What can I add to my proguard config file to avoid this that won't oblige me to rename all these methods?

  • An annotation I could add to the method and have proguard take notice of?
  • Somehow specify these types of methods referenced from xml?
  • I suppose I can add a false reference in the code, but would like to avoid that if I can as I won't always remember to put it in!

I have looked through the proguard examples for Android and can't see anything for this particular need.


回答1:


This seems to be the best answer, as it is 100% robust to naming of such methods:

# This will avoid all the onClick listeners referenced from XML Layouts from being removed
-keepclassmembers class * extends android.app.Activity { 
       public void *(android.view.View); 
}

Hope it helps.




回答2:


-keepclasseswithmembers class * {
   public void onSearchClicked(android.view.View );
}

but double check it from proguard doc : http://proguard.sourceforge.net/index.html#/manual/refcard.html




回答3:


I use:

-keepclassmembers class * extends android.app.Activity { 
       public void on*Click(android.view.View); 
}

and then I name all onClick methods like: onCancelBtnClick(), onBackgroundClick(), etc.



来源:https://stackoverflow.com/questions/6216685/android-proguard-how-to-keep-onclick-handlers-only-referenced-from-xml-layouts

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