windowmanager和window添加view的区别

2025-04-29 14:38:01
推荐回答(1个)
回答1:

WindowManager中有个添加View的函数:

public void addView(View view, ViewGroup.LayoutParams params)

Window中有个添加View的函数:

public void addContentView(View view, ViewGroup.LayoutParams params)

弄清楚这两个类和这两个函数的作用设计到Android整个Surface系统,这里不详述,只作说明,供自己记录。

事实上,这两个函数是Activity上显示View至关重要的控制函数,它们在框架
层已经有了明确的分工。查看这两个函数的调用过程可以发现addView的调用是针对ViewRootImpl的,也就是它添加的View相当于最底层的
PhoneWindow.DecorView;而addContentView最终指向了ViewGroup.addView(childView)。下
面用实验进行验证:

activity_main.xml

[java] view plain copy
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:gravity="center"
android:orientation="vertical" >

android:id="@+id/text1"
android:layout_width="match_parent"
android:layout_height="200dp"
android:background="#ff0088"
android:text="@string/hello_world" />



MainActivity.java

[java] view plain copy
public class MainActivity extends Activity {

private ImageView mImageView;

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
}
如果只有上述内容,这个Activity的效果图和View树如下:

View树和layout布局是相一致的。

现在我们使用addContentView()来添加新的内容:

[java] view plain copy
public class MainActivity extends Activity {

private ImageView mImageView;

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);

mImageView = (ImageView) this.findViewById(R.id.text1);
ImageView m = new ImageView(this);
m.setBackgroundColor(Color.BLUE);
getWindow().addContentView(m, new
ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT,200));


此时它的效果图和View树如下:

我们发现,新添加的内容是和layout的根视图是平等的,这是这个使用这个函数必须要明白的,也就是说使用addContentView添加的内容等效于setContentView(R.layout.main_activity)。

现在我们使用addView()来添加新的内容:

[java] view plain copy
public class MainActivity extends Activity {

private ImageView mImageView;

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);

mImageView = (ImageView) this.findViewById(R.id.text1);
ImageView m = new ImageView(this);
m.setBackgroundColor(Color.BLUE);
// getWindow().addContentView(m, new
// ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT,200));
WindowManager.LayoutParams wl = new WindowManager.LayoutParams();
wl.height = 200;
wl.width = WindowManager.LayoutParams.MATCH_PARENT;
getWindowManager().addView(m, wl);
}
}
此时它的效果图和View树如下:

而且Hierarchy View工具不能显示这个View树,原因就是因为addView添加的内容等同于所有视图的根视图DecorView:

如上,PhoneWindow$DecorView中这个DecorView是所有视图的根视图,而使用addView添加的内容等效于DecorView,明白这一点对于使用这个函数至关重要。
http://blog.csdn.net/u012604322/article/details/17247173