注意到AndroidStudio会提示 findViewById 不需要进行强制类型转换.
compileSdkVersion 26+
buildToolsVersion "26+"
查看findViewById方法.
/** * Finds the first descendant view with the given ID, the view itself if * the ID matches {@link #getId()}, or {@code null} if the ID is invalid * (< 0) or there is no matching view in the hierarchy. * <p> * <strong>Note:</strong> In most cases -- depending on compiler support -- * the resulting view is automatically cast to the target class type. If * the target class type is unconstrained, an explicit cast may be * necessary. * * @param id the ID to search for * @return a view with given ID if found, or {@code null} otherwise * @see View#findViewById(int) */ @Nullable public final <T extends View> T findViewById(@IdRes int id) { if (id == NO_ID) { return null; } return findViewTraversal(id); }
-----------------------------------------------------------------------------------------------------------------------
compileSdkVersion 25-
buildToolsVersion "25-"
需要强制转换时的方法.
/** * 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); }
可以发现重点就是 <T extends View> T Java的泛型自动类型推断 可以避免类型强制转换.
必须使用
compileSdkVersion 26及以上
buildToolsVersion " 26及以上"