From the start of Hello World's first Android app, Activity is automatically generated, layout is automatically generated, the layout is modified directly, and in Activity, Findviewbyid () finds the view and processes the appropriate business logic. So Setcontentview (), how does it work?
~ ~ Enter the activity of the Setcontentview Source:
public void Setcontentview (int layoutresid) { GetWindow (). Setcontentview (LAYOUTRESID); Initactionbar (); }
You can see that the window is captured and then called the window's Setcontentview.
The implementation class for Window here is Phonewindow (package com.android.internal.policy.impl;), and we look directly at its implementation:
@Override public void Setcontentview (int layoutresid) { if (mcontentparent = = null) { Installdecor (); } else { mcontentparent.removeallviews (); } Mlayoutinflater.inflate (Layoutresid, mcontentparent); Final Callback cb = Getcallback (); if (CB! = null &&!isdestroyed ()) { cb.oncontentchanged ();} }
As you can see, first to determine whether mcontentparent is null, is to call Installdecor (), otherwise remove all of its inner sub-views, We then put our incoming layout into mcontentparent by Layoutinflater.inflate.
From here it can be seen that mcontentparent is a viewgroup and wraps our entire layout file, and Installdecor () estimate is to initialize our mcontentparent, and we will verify it.
Next, through the Getcallback to get a callback object, in fact, this gets to this callback is we activity ourselves, you can go to see our activity is to achieve the callback interface.
This callback is obviously a callback, and when the Phonewindow receives a system distribution to its touch, IO, menu and other related events, it can callback the corresponding activity for processing. As for what methods callback can call back, look at the declaration method of this interface. Of course, this is not our key, because our Setcontentview inside just callback oncontentchanged, and oncontentchanged in activity is empty implementation.
OK, then go to our Installdecor ()
private void Installdecor () { if (Mdecor = = null) { Mdecor = Generatedecor (); Mdecor.setdescendantfocusability (viewgroup.focus_after_descendants); Mdecor.setisrootnamespace (true); //... } } if (mcontentparent = = null) { mcontentparent = generatelayout (Mdecor); Mtitleview = (TextView) Findviewbyid (com.android.internal.r.id.title); if (Mtitleview! = null) { //hides according to Feature_no_title, or sets the value of Mtitleview //... } else { Mactionbar = ( Actionbarview) Findviewbyid (Com.android.internal.r.id.action_bar); if (Mactionbar! = null) { //Set Actionbar title, Icon for God Horse; initialize some display of Actionbar according to feature /... } }}
The code here is long, removing some of the code that initializes the Actionbar-style god horse.
You can see that this not only initializes the mcontentparent, but also first calls Generatedecor (); Initializes a mdecor,mdecor that is the Decorview object, which is the Framelayout subclass.
The way to get the focus after getting Mdecor is to acquire it only when its descendants are not needed.
Then through the Generatelayout (Mdecor), the Mdecor as parameters, and then get to our mcontentparent;
In the next, we start to get the control through Findviewbyid, and here the Findviewbyid code is this:
Public View Findviewbyid (int id) { return Getdecorview (). Findviewbyid (ID); }
The Getdecorview returned is our Mdecor.
Here we assume that the first to initialize the Mdecor, and then initialize the mcontentparent through Mdecor, then Mdecor can use the Findviewbyid method. Then I think that the method of initializing the Mdecor
In Generatedecor (), the layout or control must be placed for our Mdecor (the simplest is to use inflate to press the layout file), and mcontentparent may be a child view in Mdecor.
Isn't that so?
Let's take a look first. Implementation of the Generatedecor () method:
protected Decorview Generatedecor () {
return New Decorview (GetContext (),-1);
}
Public Decorview (context context, int featureid) {
super (context);
Mfeatureid = Featureid; }
Unfortunately, our Generatedecor () just initialized a Framelayout object, and did not press into the layout file inside it, it seems that our guess some problems, but nothing, since this method is not, then generatelayout (Mdecor); The layout file must be set, and the name is similar.
Protected ViewGroup generatelayout (Decorview decor) {//Apply data from current theme. TypedArray a = Getwindowstyle (); //... Window_windowisfloating,window_windownotitle,window_windowactionbar////First through the various properties set in WindowStyle, Requestfeature to Window or setflags if (A.getboolean (Com.android.internal.r.styleable.window_windownotitle, False)) {requestfeature (feature_no_title); }//... if (A.getboolean (Com.android.internal.r.styleable.window_windowfullscreen, False)) {SETF Lags (Flag_fullscreen, Flag_fullscreen & (~getforcedwindowflags ())); } //... Determine if menukey windowmanager.layoutparams params = getattributes () is required based on the current version of the SDK; Set the mode of the Params.softinputmode soft keyboard through the properties set in a and//if you are currently floating activity, set flag_dim_behind in the params and record the value of Dimamount. As well as the params.windowanimations record Windowanimationstyle//inflate the window decor. int Layoutresource; int features = GetlocAlfeatures (); System.out.println ("features:0x" + integer.tohexstring (Features)); if ((Features & (1 << feature_left_icon) | (1 << feature_right_icon))) ! = 0) {if (misfloating) {Typedvalue res = new Typedvalue (); GetContext (). Gettheme (). Resolveattribute (Com.android.internal.r.attr.dialogtitleiconsdecorlayout, Res, true); Layoutresource = Res.resourceid; } else {layoutresource = com.android.internal.r.layout.screen_title_icons; }//XXX Remove This once action bar supports these features. Removefeature (Feature_action_bar); System.out.println ("Title icons!"); } else if ((Features & (1 << feature_progress) | (1 << feature_indeterminate_progress))) ! = 0 && (features & (1 << feature_action_bar)) = = 0) {//Special case for a W Indow withOnly a progress bar (and title). XXX need to has a no-title version of embedded Windows. Layoutresource = com.android.internal.r.layout.screen_progress; System.out.println ("progress!"); } else if ((Features & (1 << feature_custom_title)) = 0) {//Special case for a window with a Custo M title. If the window is floating, we need a dialog layout if (misfloating) {Typedvalue res = new Ty Pedvalue (); GetContext (). Gettheme (). Resolveattribute (Com.android.internal.r.attr.dialogcustomtitledecorlayout, Res, true); Layoutresource = Res.resourceid; } else {layoutresource = Com.android.internal.r.layout.screen_custom_title; }//XXX Remove This once action bar supports these features. Removefeature (Feature_action_bar); } else if ((Features & (1 << feature_no_titLE)) = = 0) {//If no other features and is embedded, only need a title. If the window is floating, we need a dialog layout if (misfloating) {Typedvalue res = new Ty Pedvalue (); GetContext (). Gettheme (). Resolveattribute (Com.android.internal.r.attr.dialogtitledecorlayout, Res, true); Layoutresource = Res.resourceid; } else if ((Features & (1 << feature_action_bar)) = 0) {Layoutresource = COM.ANDROID.INTERNAL.R . Layout.screen_action_bar; } else {layoutresource = Com.android.internal.r.layout.screen_title; }//System.out.println ("title!"); } else if ((Features & (1 << feature_action_mode_overlay)) = 0) {Layoutresource = Com.android.inter Nal. R.layout.screen_simple_overlay_action_mode; } else {//Embedded, so no decoration is needed. LayoutresOurce = Com.android.internal.r.layout.screen_simple; System.out.println ("simple!"); } View in = Mlayoutinflater.inflate (Layoutresource, NULL); Decor.addview (in, New Viewgroup.layoutparams (Match_parent, match_parent)); ViewGroup contentparent = (viewgroup) Findviewbyid (id_android_content); ... return contentparent; } }
The code is also long, first getwindowstyle in the current window's theme to get the properties defined in our window. Specific reference: \frameworks\base\core\res\res\values\attrs.xml
<!--the set of attributes that describe a Windows ' s theme. -- <declare-styleable name= "window" > <attr name= "Windowbackground"/> <attr name= " Windowcontentoverlay "/> <attr name=" Windowframe "/> <attr name= " Windownotitle "/> < attr name= "Windowfullscreen"/> <attr name= "Windowoverscan"/> <attr name= "windowisfloating"/ > <attr name= "windowistranslucent"/> <attr name= "Windowshowwallpaper"/> <attr Name = "Windowanimationstyle"/> <attr name= "Windowsoftinputmode"/> <attr name= " Windowdisablepreview "/> <attr name=" Windownodisplay "/> <attr name= " TextColor "/> <attr name= "backgrounddimenabled"/> <attr name= "Backgrounddimamount"/>
Then based on the values of these attributes, the various requestfeature,setflags of our window and so on. So here is the solution we set theme for activity, as for theme generally can be set in androidmanifest inside.
Next to the key section, 21-75 lines: By the features and misfloating judgment, for Layoutresource to assign value, as to the value can be r.layout.screen_custom_title; R.layout.screen_action_bar, wait. As for features, in addition to theme, we can also requestfeature before the activity's OnCreate Setcontentview, explaining that Why do I need to call Requestfeature before Setcontentview to set up fullscreen?
After getting Layoutresource, 78 lines, through the Layoutinflater to transform the layout into a view, add to our decor, that is, the incoming Mdecor.
Next 81 lines: Pass through Mdecor.findviewbyid incoming r.id.content (believe this ID everybody more or less have heard of), return Mdecor (layout) The ID is content of view, General is framelayout.
OK, you can see our Mdecor is a framelayout, and then according to theme to choose the layout file in the system, the layout file through the inflate into view, added to the Mdecor The layout file contains a framelayout with the content ID and returns its reference to Mcontentparent.
After our mcontentparent has value, return to the source of Phonewindow Setcontentview before returning to view:
With Mcontentparent, we add the layout file we wrote to the Mcontentparent by Inflater.
About R.LAYOUT.XXX can be viewed inside the frameworks\base\core\res\res\layout.
Example: R.layout.screen_custom_title.xml
<?xml version= "1.0" encoding= "Utf-8"?><!--This was a custom layout for a screen.--><linearlayout xmlns: Android= "http://schemas.android.com/apk/res/android" android:orientation= "vertical" android:fitssystemwindows= " True "> <!--popout Bar for action modes-<viewstub android:id=" @+id/action_mode_bar_stub " Android:inflatedid= "@+id/action_mode_bar" android:layout= "@layout/action_mode_bar" Android:lay Out_width= "Match_parent" android:layout_height= "wrap_content"/> <framelayout android:id= "@android: I D/title_container "android:layout_width=" match_parent "android:layout_height="? Android:attr/windowtitlesiz E "style="? Android:attr/windowtitlebackgroundstyle "> </FrameLayout> <framelayout android:id=" @and Roid:id/content "android:layout_width=" match_parent "android:layout_height=" 0dip "Android:layout_wei ght= "1" android:foregroundgRavity= "Fill_horizontal|top" android:foreground= "Android:attr/windowcontentoverlay"/></LinearLayout>
The title_container above is a container for customizing the title, and the following content is the container for placing the layout we set. About the custom title example, we can Baidu under.
Here, our Setcontentview analysis is complete, we can review:
First initialize the Mdecor, that is, Decorview is a subclass of Framelayout. is the root view of our entire window.
Then, based on the value of the attribute in theme, select the appropriate layout and infalter.inflater into our mdecor.
In these layouts, Actionbar,title is typically included, and a framelayout with the content ID.
Finally, the layout we set in the activity is infalter.inflater into our framelayout with the content of the ID.
Above transfer from: http://blog.csdn.net/lmj623565791/article/details/41894125
Get the root view method from the current activity:
getWindow().getDecorView().findViewById(android.R.id.content)
GetWindow (). Getdecorview () is the root view, of course, with Activity.getWindow.getDecorView () to express the meaning more clearly.
Here's to the main point, Android. R.id.content, this ID corresponds to what ghost, this is the root view in the Setcontentview to put the layout of the container, it is a linear layout,
(ViewGroup) findViewById(android.R.id.content)Can get hung in an Activity Content section linearlayout.
:
This is basically clear, then the official given the corresponding demo code, it seems not so strange /* * Copyright (C) The Android Open Source Project
* * Licensed under the Apache License, Version 2.0 (the "License"); * You are not a use this file except in compliance with the License. * Obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * unless required by appli Cable law or agreed into writing, software * Distributed under the License is distributed on a "as is" BASIS, * without Warranties or CONDITIONS of any KIND, either express OR implied. * See the License for the specific language governing permissions and * limitations under the License. */package Com.example.android.ui;import Com.example.android.displayingbitmaps.buildconfig;import Com.example.android.util.utils;import Android.os.bundle;import Android.support.v4.app.fragmentactivity;import android.support.v4.app.fragmenttransaction;/** * Simple fragmentactivity-to-hold the main {@link imagegridfragment} and N OT much else. */public class Imagegridactivity extends Fragmentactivity {private static final String TAG = "ImagegridactIvity "; @Override protected void OnCreate (Bundle savedinstancestate) {if (buildconfig.debug) {Utils.enables Trictmode (); } super.oncreate (Savedinstancestate); if (Getsupportfragmentmanager (). Findfragmentbytag (TAG) = = null) {final fragmenttransaction ft = Getsupportfrag Mentmanager (). BeginTransaction (); Ft.add (Android. R.id.content, New Imagegridfragment (), TAG);
Do not attempt to go to your own project to find the above ID, is the system
Ft.commit (); } }}
Setcontentview () Summary of Android activity