Android 프로젝트를 생성하면 MainActivity 클래스의 onCreate() 메서드에서 setContentView() 메서드를 호출하는 코드가 기본으로 생성됩니다. setContentView() 메서드가 정확히 어떤 작업을 담당하는 것인지 알지 못한 채 그냥 "setContentView() 메서드에 전달한 Layout 파일이 파싱되고, View 인스턴스가 생성되겠지?" 라고만 생각했었는데, Android 의 View System 에 대해 좀 더 알고 싶어져서 과연 setContentView() 메서드는 내부적으로 어떤 동작을 하는지 분석해보기로 했습니다.
총 9단계로 setContentView() 메서드를 분석하였습니다.
1. MainActivity 가 상속받은 AppCompatActivity 의 setContentView 메서드를 호출합니다.
2. AppCompatDelegate class 를 상속받은 AppCompatDelegateImpl instance 에 setContentView 작업을 위임합니다.
3. ensureSubDecor() 메서드 내부에서 기존의 View tree 인 DecorView -> LinearLayout(screen_simple.xml root View) → FrameLayout(sreen_simple.xml android.R.id.content View) 에서
DecorView → LinearLayout(screen_simple.xml 내의 root View) → FrameLayout(sreen_simple.xml 내에 선언된 View) → FitWindowLinearLayout(abc_screen_simple.xml 내의 root View 이며, subDecor) → ContentFrameLayout(abc_screen_content_include.xml 내의 root View 이며, android.R.id.content id 를 가진 View)
계층 구조를 생성한 후 기존의 contentView 인 FrameLayout 의 id 를 NO_ID(-1) 로 설정하고 새로운 contentView 인 ContentFrameLayout 의 id 를 android.R.id.content 로 설정합니다.
subDecor 라는 이름을 사용한 이유는 정확히 알 수 없지만 새로운 contentView 를 호스팅한다는 의미로 부수적인 DecorView 라는 의미로 subDecor 로 작성하지 않았을까 추측됩니다.
4. subDecor 하위의 View 중 android.R.id.content ID 를 가진 View(ContentFrameLayout)를 찾아서 연결된 모든 View 를 제거합니다.
5. R.layout.activity_main.xml 의 View 계층 구조를 inflate 하기 위해 LayoutInflater instance 의 inflate 메서드를 호출합니다.
6. tryInflatePrecompiled() 메서드를 호출하여 미리 생성된 CompiledView 클래스를 통해 View inflate 를 시도합니다.
7. tryInflatePrecompiled() 메서드는 mUseCompiledView flag 가 true 인 경우 정상 실행됩니다.
mUseCompiledView flag 가 true 인 경우는 @TestApi 인 setPrecompiledLayoutsEnabledForTesting() 메서드가 실행된 경우입니다.
mUseCompiledView flag 가 true 인 경우에는 리플렉션을 통해 미리 생성된 CompiledView 클래스 파일의 inflate 메서드를 호출하여 View 를 inflate 한 후, inflate 된 View 를 contentView 에 attach 한 후 inflate 된 View 를 반환합니다.
mUseCompiledView flag 가 false 인 경우는 null 을 반환합니다.
8. tryInflatePrecompiled() 메서드를 통해 정상적으로 inflate 되었다면 해당 View 를 반환하며, inflate 하지 못했다면 R.layout.activity_main.xml 을 파싱할 XmlResourceParser instance 를 생성한 후 inflate 를 시도합니다.
9. parser 를 root View 의 START_TAG(예: <ConstraintLayout>)을 가리키도록 이동 시킨 후 태그 이름을 가져온 후 태그 이름이 merge 인지 확인한 후 contentView 가 null 이거나 attachToRoot flag 값이 false 인 경우 InflateException 예외를 발생시킵니다.
태그 이름이 merge 가 아닌 경우 createViewFromTag() 메서드를 호출합니다. createViewFromTag() 메서드 내에서 tryCreateView() 메서드를 호출합니다.
tryCreateView() 메서드 내에서 AppCompatDelegateImpl instance 의 onCreateView() 메서드를 호출합니다.
onCreateView() 메서드 내에서 AppCompatViewInflater instance 의 createView() 메서드를 호출합니다.
createView() 메서드 내에서 switch-case 문을 통해 parser 를 통해 가져운 태그 이름에 맞는 구문을 찾은 후 해당 View instance 를 생성하여 반환합니다.(Material Theme 이 적용된 경우에는 AppCompat View 를 상속받은 Material View 가 생성하여 반환합니다.) 만약 태그 이름과 일치하는 case 문을 찾지 못했다면 null 을 반환합니다.
root View instance 를 정상적으로 생성했다면 재귀 호출을 통해 하위 태그들을 순회하며 모든 View instance 를 생성합니다.
결론
setContentView() 메서드의 코드를 분석하고 보니 왜 메서드 이름을 setContentView 라고 하였는지 알 것 같았습니다.
해당 글에는 포함되어있지 않은 내용 중 하나는 정확히 분석하진 않았지만 ConstraintLayout 과 같은 기본 View 클래스가 아닌 것은 Reflection 을 사용하는 코드가 존재하는 것으로 보아 Reflection 을 통해 View 인스턴스를 생성하는 것이 아닐까 추측됩니다.
분석에 사용된 코드는 아래와 같습니다.
public class DataBindingUtil {
public static <T extends ViewDataBinding> T setContentView(@NonNull Activity activity, int layoutId) {
return setContentView(activity, layoutId, sDefaultComponent);
}
public static <T extends ViewDataBinding> T setContentView(@NonNull Activity activity,
int layoutId, @Nullable DataBindingComponent bindingComponent) {
activity.setContentView(layoutId);
View decorView = activity.getWindow().getDecorView();
ViewGroup contentView = (ViewGroup) decorView.findViewById(android.R.id.content);
return bindToAddedViews(bindingComponent, contentView, 0, layoutId);
}
}
AppCompatActivity 의 AppCompatDelegate instance 에 setContentView 작업을 위임합니다.
public class AppCompatActivity extends FragmentActivity {
private AppCompatDelegate mDelegate;
@NonNull
public AppCompatDelegate getDelegate() {
if (mDelegate == null) {
mDelegate = AppCompatDelegate.create(this, this);
}
return mDelegate;
}
@Override
public void setContentView(@LayoutRes int layoutResID) {
initViewTreeOwners();
getDelegate().setContentView(layoutResID);
}
}
Activity 가 AppComppatActivity 를 상속받는 경우 기존 DecorView 이외에 ContentView 를 호스팅하는 SubDecorView 를 중간에 삽입하며 XML 파일을 파싱하여 View 를 inflate 하여서 ContentView 에 Root View 를 Attach 하도록 메서드를 호출합니다.
class AppCompatDelegateImpl extends AppCompatDelegate {
@Override
public void setContentView(int resId) {
ensureSubDecor();
ViewGroup contentParent = mSubDecor.findViewById(android.R.id.content);
contentParent.removeAllViews();
LayoutInflater.from(mContext).inflate(resId, contentParent);
mAppCompatWindowCallback.bypassOnContentChanged(mWindow.getCallback());
}
@Override
public View createView(View parent, final String name, @NonNull Context context, @NonNull AttributeSet attrs) {
if (mAppCompatViewInflater == null) {
TypedArray a = mContext.obtainStyledAttributes(R.styleable.AppCompatTheme);
String viewInflaterClassName =
a.getString(R.styleable.AppCompatTheme_viewInflaterClass);
if (viewInflaterClassName == null) {
// Set to null (the default in all AppCompat themes). Create the base inflater
// (no reflection)
mAppCompatViewInflater = new AppCompatViewInflater();
} else {
try {
Class<?> viewInflaterClass =
mContext.getClassLoader().loadClass(viewInflaterClassName);
mAppCompatViewInflater =
(AppCompatViewInflater) viewInflaterClass.getDeclaredConstructor()
.newInstance();
} catch (Throwable t) {
Log.i(TAG, "Failed to instantiate custom view inflater "
+ viewInflaterClassName + ". Falling back to default.", t);
mAppCompatViewInflater = new AppCompatViewInflater();
}
}
}
boolean inheritContext = false;
if (IS_PRE_LOLLIPOP) {
if (mLayoutIncludeDetector == null) {
mLayoutIncludeDetector = new LayoutIncludeDetector();
}
if (mLayoutIncludeDetector.detect(attrs)) {
// The view being inflated is the root of an <include>d view, so make sure
// we carry over any themed context.
inheritContext = true;
} else {
inheritContext = (attrs instanceof XmlPullParser)
// If we have a XmlPullParser, we can detect where we are in the layout
? ((XmlPullParser) attrs).getDepth() > 1
// Otherwise we have to use the old heuristic
: shouldInheritContext((ViewParent) parent);
}
}
return mAppCompatViewInflater.createView(parent, name, context, attrs, inheritContext,
IS_PRE_LOLLIPOP, /* Only read android:theme pre-L (L+ handles this anyway) */
true, /* Read read app:theme as a fallback at all times for legacy reasons */
VectorEnabledTintResources.shouldBeUsed() /* Only tint wrap the context if enabled */
);
}
}
미리 생성된 CompiledView 클래스가 있는 경우 XML Parsing 을 하지 않도록 하고, 미리 생성된 CompiledView 클래스가 없는 경우 XML Parsing 을 하여 재귀호출을 통해 XML 에 선언된 모든 View 를 인스턴스로 생성합니다.
public abstract class LayoutInflater {
public View inflate(@LayoutRes int resource, @Nullable ViewGroup root) {
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) + ")");
}
View view = tryInflatePrecompiled(resource, res, root, attachToRoot);
if (view != null) {
return view;
}
XmlResourceParser parser = res.getLayout(resource);
try {
return inflate(parser, root, attachToRoot);
} finally {
parser.close();
}
}
private @Nullable View tryInflatePrecompiled(@LayoutRes int resource, Resources res, @Nullable ViewGroup root, boolean attachToRoot) {
if (!mUseCompiledView) {
return null;
}
Trace.traceBegin(Trace.TRACE_TAG_VIEW, "inflate (precompiled)");
// Try to inflate using a precompiled layout.
String pkg = res.getResourcePackageName(resource);
String layout = res.getResourceEntryName(resource);
try {
Class clazz = Class.forName("" + pkg + ".CompiledView", false, mPrecompiledClassLoader);
Method inflater = clazz.getMethod(layout, Context.class, int.class);
View view = (View) inflater.invoke(null, mContext, resource);
if (view != null && root != null) {
// We were able to use the precompiled inflater, but now we need to do some work to
// attach the view to the root correctly.
XmlResourceParser parser = res.getLayout(resource);
try {
AttributeSet attrs = Xml.asAttributeSet(parser);
advanceToRootNode(parser);
ViewGroup.LayoutParams params = root.generateLayoutParams(attrs);
if (attachToRoot) {
root.addView(view, params);
} else {
view.setLayoutParams(params);
}
} finally {
parser.close();
}
}
return view;
} catch (Throwable e) {
if (DEBUG) {
Log.e(TAG, "Failed to use precompiled view", e);
}
} finally {
Trace.traceEnd(Trace.TRACE_TAG_VIEW);
}
return null;
}
public View inflate(XmlPullParser parser, @Nullable ViewGroup root, boolean attachToRoot) {
synchronized (mConstructorArgs) {
Trace.traceBegin(Trace.TRACE_TAG_VIEW, "inflate");
final Context inflaterContext = mContext;
final AttributeSet attrs = Xml.asAttributeSet(parser);
Context lastContext = (Context) mConstructorArgs[0];
mConstructorArgs[0] = inflaterContext;
View result = root;
try {
advanceToRootNode(parser);
final String name = parser.getName();
if (DEBUG) {
System.out.println("**************************");
System.out.println("Creating root view: "
+ name);
System.out.println("**************************");
}
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");
}
rInflate(parser, root, inflaterContext, attrs, false);
} else {
// 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);
}
}
if (DEBUG) {
System.out.println("-----> start inflating children");
}
// Inflate all children under temp against its context.
rInflateChildren(parser, temp, attrs, true);
if (DEBUG) {
System.out.println("-----> done inflating children");
}
// We are supposed to attach all the views we found (int temp)
// to root. Do that now.
if (root != null && attachToRoot) {
root.addView(temp, params);
}
// Decide whether to return the root that was passed in or the
// top view found in xml.
if (root == null || !attachToRoot) {
result = temp;
}
}
} catch (XmlPullParserException e) {
final InflateException ie = new InflateException(e.getMessage(), e);
ie.setStackTrace(EMPTY_STACK_TRACE);
throw ie;
} catch (Exception e) {
final InflateException ie = new InflateException(
getParserStateDescription(inflaterContext, attrs)
+ ": " + e.getMessage(), e);
ie.setStackTrace(EMPTY_STACK_TRACE);
throw ie;
} finally {
// Don't retain static reference on context.
mConstructorArgs[0] = lastContext;
mConstructorArgs[1] = null;
Trace.traceEnd(Trace.TRACE_TAG_VIEW);
}
return result;
}
}
@UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
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();
}
try {
View view = tryCreateView(parent, name, context, attrs);
if (view == null) {
final Object lastContext = mConstructorArgs[0];
mConstructorArgs[0] = context;
try {
if (-1 == name.indexOf('.')) {
view = onCreateView(context, parent, name, attrs);
} else {
view = createView(context, name, null, attrs);
}
} finally {
mConstructorArgs[0] = lastContext;
}
}
return view;
} catch (InflateException e) {
throw e;
} catch (ClassNotFoundException e) {
final InflateException ie = new InflateException(
getParserStateDescription(context, attrs)
+ ": Error inflating class " + name, e);
ie.setStackTrace(EMPTY_STACK_TRACE);
throw ie;
} catch (Exception e) {
final InflateException ie = new InflateException(
getParserStateDescription(context, attrs)
+ ": Error inflating class " + name, e);
ie.setStackTrace(EMPTY_STACK_TRACE);
throw ie;
}
}
@UnsupportedAppUsage(trackingBug = 122360734)
@Nullable
public final View tryCreateView(@Nullable View parent, @NonNull String name,
@NonNull Context context,
@NonNull AttributeSet attrs) {
if (name.equals(TAG_1995)) {
// Let's party like it's 1995!
return new BlinkLayout(context, attrs);
}
View 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);
}
return view;
}
void rInflate(XmlPullParser parser, View parent, Context context,
AttributeSet attrs, boolean finishInflate) throws XmlPullParserException, IOException {
final int depth = parser.getDepth();
int type;
boolean pendingRequestFocus = false;
while (((type = parser.next()) != XmlPullParser.END_TAG ||
parser.getDepth() > depth) && type != XmlPullParser.END_DOCUMENT) {
if (type != XmlPullParser.START_TAG) {
continue;
}
final String name = parser.getName();
if (TAG_REQUEST_FOCUS.equals(name)) {
pendingRequestFocus = true;
consumeChildElements(parser);
} else if (TAG_TAG.equals(name)) {
parseViewTag(parser, parent, attrs);
} else if (TAG_INCLUDE.equals(name)) {
if (parser.getDepth() == 0) {
throw new InflateException("<include /> cannot be the root element");
}
parseInclude(parser, context, parent, attrs);
} else if (TAG_MERGE.equals(name)) {
throw new InflateException("<merge /> must be the root element");
} else {
final View view = createViewFromTag(parent, name, context, attrs);
final ViewGroup viewGroup = (ViewGroup) parent;
final ViewGroup.LayoutParams params = viewGroup.generateLayoutParams(attrs);
rInflateChildren(parser, view, attrs, true);
viewGroup.addView(view, params);
}
}
if (pendingRequestFocus) {
parent.restoreDefaultFocus();
}
if (finishInflate) {
parent.onFinishInflate();
}
}
}
태그에서 추출한 View 이름을 통해 실제로 View 인스턴스를 생성하는 역할을 합니다.
public class AppCompatViewInflater {
@Nullable
public final View createView(@Nullable View parent, @NonNull final String name,
@NonNull Context context,
@NonNull AttributeSet attrs, boolean inheritContext,
boolean readAndroidTheme, boolean readAppTheme, boolean wrapContext) {
final Context originalContext = context;
// We can emulate Lollipop's android:theme attribute propagating down the view hierarchy
// by using the parent's context
if (inheritContext && parent != null) {
context = parent.getContext();
}
if (readAndroidTheme || readAppTheme) {
// We then apply the theme on the context, if specified
context = themifyContext(context, attrs, readAndroidTheme, readAppTheme);
}
if (wrapContext) {
context = TintContextWrapper.wrap(context);
}
View view = null;
// We need to 'inject' our tint aware Views in place of the standard framework versions
switch (name) {
case "TextView":
view = createTextView(context, attrs);
verifyNotNull(view, name);
break;
case "ImageView":
view = createImageView(context, attrs);
verifyNotNull(view, name);
break;
case "Button":
view = createButton(context, attrs);
verifyNotNull(view, name);
break;
case "EditText":
view = createEditText(context, attrs);
verifyNotNull(view, name);
break;
case "Spinner":
view = createSpinner(context, attrs);
verifyNotNull(view, name);
break;
case "ImageButton":
view = createImageButton(context, attrs);
verifyNotNull(view, name);
break;
case "CheckBox":
view = createCheckBox(context, attrs);
verifyNotNull(view, name);
break;
case "RadioButton":
view = createRadioButton(context, attrs);
verifyNotNull(view, name);
break;
case "CheckedTextView":
view = createCheckedTextView(context, attrs);
verifyNotNull(view, name);
break;
case "AutoCompleteTextView":
view = createAutoCompleteTextView(context, attrs);
verifyNotNull(view, name);
break;
case "MultiAutoCompleteTextView":
view = createMultiAutoCompleteTextView(context, attrs);
verifyNotNull(view, name);
break;
case "RatingBar":
view = createRatingBar(context, attrs);
verifyNotNull(view, name);
break;
case "SeekBar":
view = createSeekBar(context, attrs);
verifyNotNull(view, name);
break;
case "ToggleButton":
view = createToggleButton(context, attrs);
verifyNotNull(view, name);
break;
default:
// The fallback that allows extending class to take over view inflation
// for other tags. Note that we don't check that the result is not-null.
// That allows the custom inflater path to fall back on the default one
// later in this method.
view = createView(context, name, attrs);
}
if (view == null && originalContext != context) {
// If the original context does not equal our themed context, then we need to manually
// inflate it using the name so that android:theme takes effect.
view = createViewFromTag(context, name, attrs);
}
if (view != null) {
// If we have created a view, check its android:onClick
checkOnClickListener(view, attrs);
backportAccessibilityAttributes(context, view, attrs);
}
return view;
}
}
'android > Android 코드' 카테고리의 다른 글
Lifecycle (1) | 2023.12.27 |
---|