学习自定义View一段时间了,从开始的一窍不通到现在终于能写出点东西了,前面也写过几篇关于自定义view的博客,但是感觉这东西吧,一天不敲又忘记了,所以准备写一篇自定义View系列的博客,这也算是我这段时间学习自定义View总结的开篇,接下来还会有一系列的文章,支持我的朋友可以悄悄的点个赞,一起fighting!!!
既然是总结性的东西我们就要研究透一点,我们从源码看,不啰嗦了,开车了……
首先获取LayoutInflater的方式有两种:
方式一:
LayoutInflater inflater = LayoutInflater.from(context);
方式二:
LayoutInflater inflater = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
其实方式一的from方法里面就是通过方式二的方式实现的
*
* Obtains the LayoutInflater from the given context.
*/
public static LayoutInflater from(Context context) {
LayoutInflater LayoutInflater =
(LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
if (LayoutInflater == null) {
throw new AssertionError("LayoutInflater not found.");
}
return LayoutInflater;
}
好了,讲了怎么获取LayoutInflater实例了,我们该研究下inflater方法了,
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) + ")");
}
final XmlResourceParser parser = res.getLayout(resource);
try {
return inflate(parser, root, attachToRoot);
} finally {
parser.close();
}
}
可以看了inflater中需要传递三个参数,
Tables | Are |
---|---|
resource | 需要inflater的layout文件 |
root | root布局 |
attachToroot | 是否加到root布局中 |
先大致走一遍源码,
public View inflate(XmlPullParser parser, ViewGroup root, boolean attachToRoot) {
synchronized (mConstructorArgs) {
Trace.traceBegin(Trace.TRACE_TAG_VIEW, "inflate");
final AttributeSet attrs = Xml.asAttributeSet(parser);
Context lastContext = (Context)mConstructorArgs[0];
mConstructorArgs[0] = mContext;
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!");
}
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;
}
}
inflater中代码还不是很多,我们简单看看最主要的部分,我们可以看到这么一行代码
final View temp = createViewFromTag(root, name, inflaterContext, attrs);
当XmlPullParser解析一边读一边解析到标签的时候,就去根据名字通过反射创建一个View。
当root!=null的时候,会Create layout params that match root, if supplied(创建一个属于root的params)
params = root.generateLayoutParams(attrs);
当root=null的时候,此时的layoutParams为空,不理解也没关系,我待会会用例子讲解的。
当attachToroot=false的时候(不加入到root中)
if (!attachToRoot) {
temp.setLayoutParams(params);
}
当attachToroot=true的时候(加入到root中)
if (root != null && attachToRoot) {
root.addView(temp, params);
}
最后返回result,inflater的源码我们就大致过了一遍,接下来我会用例子一一讲解每一个用法,并且展示我们常见的一些错误。
首先我们准备一个叫botton的布局,里面就一个Button。
<?xml version="1.0" encoding="utf-8"?>
<Button xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width=wrap_content android:layout_height=wrap_content android:text=Button >
</Button>
主布局main.layout
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width=match_parent android:layout_height=match_parent android:id=@+id/id_content >
</RelativeLayout>
然后我们通过inflater加载出button然后添加到主布局id为id_content的RelativeLayout布局中,想必这对大家来说都是小菜一碟了。
public class MainActivity extends FragmentActivity {
private RelativeLayout rl_content;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main2);
rl_content= (RelativeLayout) findViewById(R.id.id_content);
LayoutInflater inflater = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
//测试一id,null,false
View view= inflater.inflate(R.layout.bottom,null,false);
rl_content.addView(view);
}
运行效果:
好了,接着我们改改button的大小,宽度改为300dp
<?xml version="1.0" encoding="utf-8"?>
<Button xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width=300dp android:layout_height=wrap_content android:text=Button >
</Button>
我们再看看效果:
没有变化咯,这是为什么呢?
我们把代码改改,传一个rl_content当做root
inflater.inflate(R.layout.bottom,rl_content,false);
rl_content.addView(view);
这时inflater会执行
params = root.generateLayoutParams(attrs);
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);
}
}
我们运行代码:
按钮终于变大了,我们可以看到,如果我们不指定button的父控件的话
android:layout_width=300dp就会失效,因为只要有layout_标签的
属性的话,必须要有父控件,不然就没有意义了。
所以如果需要android:layout_width=300dp有效的话,还可以通过在xml布局中给Button一个父布局就ok了。
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="100dp" android:layout_height="500dp" android:orientation="vertical" android:background="#00ff00" >
<Button xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width=300dp android:layout_height=wrap_content android:text="Button" >
</Button>
</LinearLayout>
这样既可~!!!!!
接下来说说以前遇到的坑了,
我们改改代码,把attachToroot改为true
LayoutInflater inflater = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View view= inflater.inflate(R.layout.bottom,rl_content,true);
rl_content.addView(view);
我们继续运行下代码:
程序直接报错了,报错信息为:
* Caused by: java.lang.IllegalStateException: The specified child already has a parent. You must call removeView() on the child’s parent first.*
大致就是说此View已经有一个父控件了,不能调用addView了。
我们看看源码当attachToroot改为true时 inflater中的代码,我们看到这么一段代码:
if (root != null && attachToRoot) {
root.addView(temp, params);
}
看到这里我们恍然大悟了,也就是说在inflater方法中已经把view加入root中了,所以再加的话会报错。
当加载的布局为merge 类型的时候,必须加root,然后attachToRoot必须为true,不然会报错:
<?xml version="1.0" encoding="utf-8"?>
<merge xmlns:android="http://schemas.android.com/apk/res/android" >
<Button android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Button" />
</merge>
如果root为空或者attachToRoot为false时,运行效果:
直接报错了~!!
报错信息大致为:
throw new InflateException("<merge /> can be used only with a valid "
+ "ViewGroup root and attachToRoot=true");
好了,讲到这里想必大家都应该对inflater方法有一个深刻的了解了,
没事多ctrl+左键吧,会有很多收获哦~!!!!3q