前言
工作時(shí)有個(gè)需求,把往Android28里面跑的代碼放到android 25上去跑,結(jié)果編譯就gg了/

image.png
在開發(fā)android 28 時(shí),用sonar檢測(cè)一個(gè)一個(gè)把強(qiáng)轉(zhuǎn)類型給刪的,現(xiàn)在又要我一個(gè)一個(gè)加回來,為什么?。?!
對(duì)啊 為什么呢。
原因
其實(shí)去高版本sdk上看,會(huì)發(fā)現(xiàn)
@Nullable
public final <T extends View> T findViewById(@IdRes int id) {
if (id == NO_ID) {
return null;
}
return findViewTraversal(id);
}
protected <T extends View> T findViewTraversal(@IdRes int id) {
if (id == mID) {
return (T) this;
}
return null;
}
而在sdk 25的版本上代碼沒有這個(gè)泛型,這也就是為什么要強(qiáng)轉(zhuǎn)啦。 那是不是我把sdk25的find同步成高版本的實(shí)現(xiàn)我就不用在代碼上改了呢!哈哈哈~
/**
* Look for a child view with the given id. If this view has the given
* id, return this view.
*
* @param id The id to search for.
* @return The view that has the given id in the hierarchy or null
*/
@Nullable
public final View findViewById(@IdRes int id) {
if (id < 0) {
return null;
}
return findViewTraversal(id);
}
/**
* {@hide}
* @param id the id of the view to be found
* @return the view of the specified id, null if cannot be found
*/
protected View findViewTraversal(@IdRes int id) {
if (id == mID) {
return this;
}
return null;
}