Android - fragment getSimpleName的坑 with proguard

  • 58
  • 0

當fragment 使用simpleName會出現的坑

當我們在Activity中添加一個Fragment時,我們通常會使用TAG作為它的id。

getFragmentManager().beginTransaction()
       .add(containerResource, fragment, fragmentTAG).commit();

一般情況下我們都會選擇類名作為這裡的fragmentTag。為了簡化,這裡的類名並不包含包名。當然前提是我們知道項目中不同的包下沒有重名的類。

public static final String TAG = MyClassFragment.class.getSimpleName();

當需要使用該fragment時,我們通過findFragmentByTag方法獲取:

fragment = getFragmentManager().findFragmentByTag(tag);

一般情況下這樣做是沒有什麼問題的,即使是在混淆後。

真的沒有問題嗎?

儘管類不同,但是它們還是可能使用相同的Tag。

How this happen?

假設現在有兩個fragment,以及它們在混淆後的類名如下:

com.mypackage1.FragmentA → com.mypackage1.a

com.mypackage2.FragmentB → com.mypackage2.a

這樣也是沒有問題的,但是如果使用simple name呢?

com.mypackage1.FragmentA → a

com.mypackage2.FragmentB → a

! ! !

也許出現這種情況的概率並不是很大,但也是有可能出現的。

為了不出現這種情況,可以有如下幾種解決方案:

使用full name
使用別名
使用字符串常量

來源:https://www.twblogs.net/a/5cc07ef7bd9eee397113d700/?lang=zh-cn