Android佈局優化,是一個老生常談的問題,之前都知道要減小布局的層級,能夠UI優化,可是知其然不知其因此然,經過釋然小師弟的LayoutInflater源碼分析,我本身又去讀了一遍源碼,對於爲何這麼作能夠對性能有一個提高,在這裏從setContentView開始,整理一下思路,作一個記錄。java
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_layout)調用setContentView方法設置佈局xml
init()
}
接下來咱們分析一下setContentView是怎麼設置xml
複製代碼
AppCompatActivity.javanode
/**
* @return The {@link AppCompatDelegate} being used by this Activity.
*/
@NonNull
public AppCompatDelegate getDelegate() {
if (mDelegate == null) {
若是爲空,建立一個AppCompatDelete
mDelegate = AppCompatDelegate.create(this, this);
}
return mDelegate;
繼續向下追AppCompatDelegate是怎麼建立的
/**
* Create an {@link androidx.appcompat.app.AppCompatDelegate} to use with {@code activity}.
*
* @param callback An optional callback for AppCompat specific events
*/
@NonNull
public static AppCompatDelegate create(@NonNull Activity activity,
@Nullable AppCompatCallback callback) {
這裏return了一個Impl,繼續追過去看
return new AppCompatDelegateImpl(activity, callback);
}
在AppCompatDelegateImpl中咱們會找到3個setContentView重載函數,這裏只貼出其中一個方法,有須要的同窗可自行查看源碼
@Override
public void setContentView(int resId) {
ensureSubDecor();
ViewGroup contentParent = mSubDecor.findViewById(android.R.id.content);
contentParent.removeAllViews();
//調用LayoutInflater把佈局放到contentParent裏面
LayoutInflater.from(mContext).inflate(resId, contentParent);
mAppCompatWindowCallback.getWrapped().onContentChanged();
}
複製代碼
到此發現SetContentViwe是通LayoutInflater.from(mContext).inflate(resId, contentParent)將佈局文件放到了contentParent中。須要進一步分析LayoutInflater的源碼,看看是如何加載的xml,爲何佈局的層級會影響性能。android
public View inflate(@LayoutRes int resource, @Nullable ViewGroup root) {
繼續查看inflate作了些什麼
return inflate(resource, root, root != null);
}
public View inflate(@LayoutRes int resource, @Nullable ViewGroup root, boolean attachToRoot) {
final Resources res = getContext().getResources();
if (DEBUG) {
Log.d(TAG, "INFLATING from resource: \"" + res.getResourceName(resource) + "\" ("
+ Integer.toHexString(resource) + ")");
}
此處調用XmlResourceParser這是一個xml解析接口以獲取xml資源
,Android默認的xml解析器是XmlPullParser
final XmlResourceParser parser = res.getLayout(resource);
try {
此處再次調用inflate的重載函數進行xml的解析
return inflate(parser, root, attachToRoot);
} finally {
parser.close();
}
}
//這裏貼出inflate重載函數的官方註釋
For performance reasons, view inflation relies heavily on pre-processing of
XML files that is done at build time. Therefore, it is not currently possible
to use LayoutInflater with an XmlPullParser over a plain XML file at runtime;
it only works with an XmlPullParser returned from a compiled resource
出於性能緣由,視圖的inflation是在構建的時候預編譯解析的。所以,當前沒法在運行時經過純XML文件在XmlPullParser中使用LayoutInflater。
此處個人理解就是佈局文件在編譯的時候,提取被解析成xml,下面看源碼中會發現,佈局文件解析是經過反射建立View對象
因爲代碼過長,貼出部分關鍵代碼
public View inflate(XmlPullParser parser, @Nullable ViewGroup root, boolean attachToRoot) {
synchronized (mConstructorArgs) {
/**省略代碼**/
//定義返回值,初始化值爲傳入的root
View result = root;
try {
// Look for the root node.
int type;
while ((type = parser.next()) != XmlPullParser.START_TAG &&
type != XmlPullParser.END_DOCUMENT) {
// Empty
}
if (type != XmlPullParser.START_TAG) {
throw new InflateException(parser.getPositionDescription()
+ ": No start tag found!");
}//對START_TAG,END_DOCUMENT,事件進行解析處理
final String name = parser.getName();//獲取當前的事件標籤
if (TAG_MERGE.equals(name)) {
if (root == null || !attachToRoot) {
throw new InflateException("<merge /> can be used only with a valid "
+ "ViewGroup root and attachToRoot=true");
}
//若是使用了merge標籤,那麼就在此進行遞歸處理。使用merge標籤需注意,必需要有父佈局而且要依賴父佈局加載,否則會報異常
rInflate(parser, root, inflaterContext, attrs, false);//此處圈起來
} else {
//若是沒有使用merge,那麼建立一個臨時的根視圖temp
// Temp is the root view that was found in the xml
final View temp = createViewFromTag(root, name, inflaterContext, attrs);
ViewGroup.LayoutParams params = null;
if (root != null) {
if (DEBUG) {
System.out.println("Creating params from root: " +
root);
}
// Create layout params that match root, if supplied
params = root.generateLayoutParams(attrs);
if (!attachToRoot) {
// Set the layout params for temp if we are not
// attaching. (If we are, we use addView, below)
temp.setLayoutParams(params);//臨時的params
}
}
/**省略代碼**/
//遞歸子佈局
rInflateChildren(parser, temp, attrs, true);
// Decide whether to return the root that was passed in or the
// top view found in xml.
if (root == null || !attachToRoot) {
result = temp;//將臨時根視圖賦值給開始定義的返回值result
}
}
/**省略代碼**/
return result;
}
}
final void rInflateChildren(XmlPullParser parser, View parent, AttributeSet attrs,
boolean finishInflate) throws XmlPullParserException, IOException {
rInflate(parser, parent, parent.getContext(), attrs, finishInflate);
}
到這裏會發現不論哪一種方式,最終都會調用rInflate()函數加載xml而後在這個函數中又會調用一個很重要的函數createViewFromTag(),接下來分析一下這個函數
View createViewFromTag(View parent, String name, Context context, AttributeSet attrs,
boolean ignoreThemeAttr) {
if (name.equals("view")) {
name = attrs.getAttributeValue(null, "class");
}
// Apply a theme wrapper, if allowed and one is specified.
if (!ignoreThemeAttr) {
final TypedArray ta = context.obtainStyledAttributes(attrs, ATTRS_THEME);
final int themeResId = ta.getResourceId(0, 0);
if (themeResId != 0) {
context = new ContextThemeWrapper(context, themeResId);
}
ta.recycle();
}
if (name.equals(TAG_1995)) {
// Let's party like it's 1995!
return new BlinkLayout(context, attrs);
}
try {
View view;
//調用Factory來建立View
if (mFactory2 != null) {
view = mFactory2.onCreateView(parent, name, context, attrs);
} else if (mFactory != null) {
view = mFactory.onCreateView(name, context, attrs);
} else {
view = null;
}
if (view == null && mPrivateFactory != null) {
view = mPrivateFactory.onCreateView(parent, name, context, attrs);
}
if (view == null) {
final Object lastContext = mConstructorArgs[0];
mConstructorArgs[0] = context;
try {
if (-1 == name.indexOf('.')) {//含有"."tag的控件 好比一些自定義view
view = onCreateView(parent, name, attrs);
} else {
view = createView(name, null, attrs);
}
} finally {
mConstructorArgs[0] = lastContext;
}
}
return view;
}
/**省略代碼**/
}
這裏首先會用Factory.onCreateView獲取一個View對象,若是獲取不到,最終會調用createView()函數建立View對象
public final View createView(String name, String prefix, AttributeSet attrs)
throws ClassNotFoundException, InflateException {
Constructor<? extends View> constructor = sConstructorMap.get(name);
if (constructor != null && !verifyClassLoader(constructor)) {
constructor = null;
sConstructorMap.remove(name);
}
Class<? extends View> clazz = null;
try {
Trace.traceBegin(Trace.TRACE_TAG_VIEW, name);
if (constructor == null) {
// Class not found in the cache, see if it's real, and try to add it
clazz = mContext.getClassLoader().loadClass(
prefix != null ? (prefix + name) : name).asSubclass(View.class);
if (mFilter != null && clazz != null) {
boolean allowed = mFilter.onLoadClass(clazz);
if (!allowed) {
failNotAllowed(name, prefix, attrs);
}
}
constructor = clazz.getConstructor(mConstructorSignature);
constructor.setAccessible(true);
sConstructorMap.put(name, constructor);
} else {
// If we have a filter, apply it to cached constructor
if (mFilter != null) {
// Have we seen this name before?
Boolean allowedState = mFilterMap.get(name);
if (allowedState == null) {
// New class -- remember whether it is allowed
clazz = mContext.getClassLoader().loadClass(
prefix != null ? (prefix + name) : name).asSubclass(View.class);
boolean allowed = clazz != null && mFilter.onLoadClass(clazz);
mFilterMap.put(name, allowed);
if (!allowed) {
failNotAllowed(name, prefix, attrs);
}
} else if (allowedState.equals(Boolean.FALSE)) {
failNotAllowed(name, prefix, attrs);
}
}
}
Object lastContext = mConstructorArgs[0];
if (mConstructorArgs[0] == null) {
// Fill in the context if not already within inflation.
mConstructorArgs[0] = mContext;
}
Object[] args = mConstructorArgs;
args[1] = attrs;
//根據獲取的構造器實例化一個View的對象
final View view = constructor.newInstance(args);
if (view instanceof ViewStub) {
// Use the same context when inflating ViewStub later.
final ViewStub viewStub = (ViewStub) view;
viewStub.setLayoutInflater(cloneInContext((Context) args[0]));
}
mConstructorArgs[0] = lastContext;
return view;
}
複製代碼
1.從第一步在onCreate中調用setContentView設置xml開始,一步一步查看源碼,能夠看到xml經過Layoutinflater解析實例化成一個View,是須要XmlPullParser解析xml,Java反射來操做建立View,這是一個很耗時的過程。若是佈局層級過於複雜,那麼遞歸調用所消耗的數據也就越長,執行反射的次數也會增長,就會帶來性能上的問題。
2.使用merge標籤能夠減小布局的嵌套,減小了佈局層級,那麼建立view的時候可讓遞歸調用的時間縮短,反射的次數減小,從而達到一個性能的優化。 3.使用約束佈局ConstraintLayout,能夠有效減小布局時候的嵌套問題性能優化
固然,UI性能的優化不止於佈局層級方面,View的過分繪製的優化,使用ViewStub進行懶加載,使用AsyncLayoutInflater異步加載佈局等。Android10中新增了一個函數tryInflatePrecompiled,能夠有效的解決佈局方面優化的問題,這個函數我就在此不作贅述了,能夠移步下方連接查看。app
感謝 「Android10源碼分析」爲何複雜佈局會產生卡頓?-- LayoutInflater詳解 釋然小師弟異步
本文未經容許禁止轉載ide