惭愧 发现已经好久没更新博客了,来一发
前面有写过一篇自定义view 主要写的是为原生的控件添加自定义的属性,其基本原理就是在代码中为原生的控件外面包一层自定义的控件,从而使系统能认识我们自定义的属性,最终达到控制原生控件的目的。这样做的目的是为了让别人用我们设计的框架时,不需要为了一个属性而去自定义view。
如果有兴趣详细了解可以参考我的这篇文章android 自定义ViewGroup之浪漫求婚
今天我们继续来研究另外一种实现方式。这种方式是小红书的欢迎页面的实现方式
首先我们还是要来看一下activity加载布局的流程,因为不管哪种方式最终都是通过在加载布局的过程中,人为的控制加载的属性,来达到我们简化开发的目的。
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
...
}
上面的代码相信大家都看的懂就不解释了,当调用setContentView方法时会去调用它的父类方法 Activity.java:
public void setContentView(int layoutResID) {
getWindow().setContentView(layoutResID);
initWindowDecorActionBar();
}
然后接着调用getWindow()的setContentView,所以我们首先要知道getWidow()是什么,依然在Activity.java中看到:
public Window getWindow() {
return mWindow;
}
所以最终是mWindow,那么mWindow是什么呢
private Window mWindow;
他是一个Window,而Window是一个抽象类,所以我们得回到Activity.java中找它的赋值语句
在attach方法中我们找到了mWindow的赋值
final void attach(Context context, ActivityThread aThread,
Instrumentation instr, IBinder token, int ident,
Application application, Intent intent, ActivityInfo info,
CharSequence title, Activity parent, String id,
NonConfigurationInstances lastNonConfigurationInstances,
Configuration config, String referrer, IVoiceInteractor voiceInteractor) {
attachBaseContext(context);
mFragments.attachHost(null /*parent*/);
mWindow = new PhoneWindow(this);
...
}
发现它其实是PhoneWindow类,因此我们去到PhoneWindow类里面看看setContentView的具体实现:
public void setContentView(int layoutResID) {
...
mLayoutInflater.inflate(layoutResID, mContentParent);
...
}
只看关键代码 发现最后是通过LayoutInflater.inflate来加载布局的,大家应该都知道 findViewById 可以用来查找控件,inflate用来查找布局,所以发现系统其实也是这样做的。
这里有个注意事项inflate的时候其实已经把布局给画到视图上了,曾经因为这个问题困扰了我一个同事好久。
而最终inflate 会调到LayoutInflater.java的inflate(int resource, ViewGroup root, boolean attachToRoot)
public View inflate(int resource, ViewGroup root, boolean attachToRoot) {
final Resources res = getContext().getResources();
if (DEBUG) {
Log.d(TAG, "INFLATING from resource: \"" + res.getResourceName(resource) + "\" ("
+ Integer.toHexString(resource) + ")");
}
final XmlResourceParser parser = res.getLayout(resource);
try {
return inflate(parser, root, attachToRoot);
} finally {
parser.close();
}
}
到这里可以发现 首先会用XmlResourceParser 去解析我们设置进来的布局参数,然后返回inflate(parser, root, attachToRoot)
这里面的代码就比较多了
public View inflate(XmlPullParser parser, ViewGroup root, boolean attachToRoot) {
synchronized (mConstructorArgs) {
Trace.traceBegin(Trace.TRACE_TAG_VIEW, "inflate");
...
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, attrs, false, false);
} else {
// Temp is the root view that was found in the xml
final View temp = createViewFromTag(root, name, attrs, false);
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
rInflate(parser, temp, attrs, true, 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) {
InflateException ex = new InflateException(e.getMessage());
ex.initCause(e);
throw ex;
} catch (IOException e) {
InflateException ex = new InflateException(
parser.getPositionDescription()
+ ": " + e.getMessage());
ex.initCause(e);
throw ex;
} finally {
// Don't retain static reference on context.
mConstructorArgs[0] = lastContext;
mConstructorArgs[1] = null;
}
Trace.traceEnd(Trace.TRACE_TAG_VIEW);
return result;
}
}
从上面代码中可以看出 会调用createViewFromTag来创建一个view,而最终也可以发现整个方法最后返回的也是这个view。因此我们继续看下这个view是怎么创建出来的:
View createViewFromTag(View parent, String name, AttributeSet attrs, boolean inheritContext) {
...
// Apply a theme wrapper, if requested.
final TypedArray ta = viewContext.obtainStyledAttributes(attrs, ATTRS_THEME);
final int themeResId = ta.getResourceId(0, 0);
if (themeResId != 0) {
viewContext = new ContextThemeWrapper(viewContext, themeResId);
}
ta.recycle();
...
try {
View view;
if (mFactory2 != null) {
view = mFactory2.onCreateView(parent, name, viewContext, attrs);
} else if (mFactory != null) {
view = mFactory.onCreateView(name, viewContext, attrs);
} else {
view = null;
}
if (view == null && mPrivateFactory != null) {
view = mPrivateFactory.onCreateView(parent, name, viewContext, attrs);
}
if (view == null) {
final Object lastContext = mConstructorArgs[0];
mConstructorArgs[0] = viewContext;
try {
if (-1 == name.indexOf('.')) {
view = onCreateView(parent, name, attrs);
} else {
view = createView(name, null, attrs);
}
} finally {
mConstructorArgs[0] = lastContext;
}
}
if (DEBUG) System.out.println("Created view is: " + view);
return view;
...
}
}
一些与主题无关的判断就暂时去掉了 重点关注下主线这里的view创建流程,发现这里新建一个view对象,然后一步一步的判读,到最后只有Factory 没有创建出view实例时才会调用它自己createView去创建view实例。然后我们在看下
Factory是什么
public interface Factory {
/**
* Hook you can supply that is called when inflating from a LayoutInflater.
* You can use this to customize the tag names available in your XML
* layout files.
*
* <p>
* Note that it is good practice to prefix these custom names with your
* package (i.e., com.coolcompany.apps) to avoid conflicts with system
* names.
*
* @param name Tag name to be inflated.
* @param context The context the view is being created in.
* @param attrs Inflation attributes as specified in XML file.
*
* @return View Newly created view. Return null for the default
* behavior.
*/
public View onCreateView(String name, Context context, AttributeSet attrs);
}
它就是一个接口,而且只有一个方法,但是注释却有好多 其实一看Hook 大致就明白了,它是一个钩子,Factory2继承自Factory所以Factory2是Factory的进一步扩充,而它的onCreateView方法可以返回一个view,搜索发现,发现在Activity.java中有实现这个接口而onCreateView返回是null,所以最终这个view的创建默认还是调用LayoutInflater的createView(name, null, attrs);
现在想当我们实现Factory这个接口,是不是就可以控制系统的控件了呢。
按照这个想法 我们来看看小红书的欢迎页面是怎么做的。
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:background="@color/white"
android:orientation="vertical" >
<com.xhs.view.parallaxpager.ParallaxContainer
android:id="@+id/parallax_container"
android:layout_width="match_parent"
android:layout_height="match_parent"/>
<ImageView
android:id="@+id/iv_man"
android:layout_width="67dp"
android:layout_height="202dp"
android:layout_alignParentBottom="true"
android:layout_centerHorizontal="true"
android:layout_marginBottom="10dp"
android:background="@drawable/intro_item_manrun_1"
android:visibility="gone" />
</RelativeLayout>
在布局中加入ParallaxContainer 这个自定义控件,它的实现如下
public void setupChildren(LayoutInflater inflater, int... childIds) {
Log.i("lly3","getChildCount ==" +getChildCount());
if (getChildCount() > 0) {
throw new RuntimeException("setupChildren should only be called once when ParallaxContainer is empty");
}
ParallaxLayoutInflater parallaxLayoutInflater = new ParallaxLayoutInflater(
inflater, getContext());
for (int childId : childIds) {
View view = parallaxLayoutInflater.inflate(childId, this);
viewlist.add(view);
}
pageCount = getChildCount();
for (int i = 0; i < pageCount; i++) {
View view = getChildAt(i);
addParallaxView(view, i);
}
updateAdapterCount();
viewPager = new ViewPager(getContext());
viewPager.setLayoutParams(new LayoutParams(LayoutParams.MATCH_PARENT,LayoutParams.MATCH_PARENT));
viewPager.setId(R.id.parallax_pager);
viewPager.setAdapter(adapter);
attachOnPageChangeListener();
addView(viewPager, 0);
}
只列出了主要的方法,源码稍后会给出
上面的方法里我们主要关心
ParallaxLayoutInflater parallaxLayoutInflater = new ParallaxLayoutInflater(
inflater, getContext());
Log.i("lly3","getChildCount == 1," +getChildCount());
for (int childId : childIds) {
View view = parallaxLayoutInflater.inflate(childId, this);
viewlist.add(view);
}
这里自定义了一个LayoutInflater 我们看下ParallaxLayoutInflater类:
public class ParallaxLayoutInflater extends LayoutInflater {
protected ParallaxLayoutInflater(LayoutInflater original, Context newContext) {
super(original, newContext);
setUpLayoutFactory();
}
private void setUpLayoutFactory() {
if (!(getFactory() instanceof ParallaxFactory)) {
setFactory(new ParallaxFactory(this, getFactory()));
}
}
@Override
public LayoutInflater cloneInContext(Context newContext) {
return new ParallaxLayoutInflater(this, newContext);
}
}
setFactory的时候用的是自己实现的Factory,从而需要实现onCreateView方法
既然都自己实现这个方法了 那岂不我们想加什么就加什么了。
以下给出小红书的欢迎页面,大家也可以到网上搜索找到。
源码