setContentView()
方法的文档中指出,这个方法会将视图添加到活动窗口并进行充气。然而,在调用setContentView()
之后,根视图的宽度和高度都为零。以下是示例:
活动类
public class MainActivity extends AppCompatActivity {
private static final String TAG = "myTag";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
View root = ((ViewGroup) this.findViewById(android.R.id.content)).getChildAt(0);
// Here I expect the root view to have been inflated and have a width and height
Log.i(TAG, "Root view width:" + root.getWidth() + " height:" + root.getHeight());
}
}
布局XML
<?xml version="1.0" encoding="utf-8"?>
<FrameLayout
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"
tools:context=".MainActivity">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Hello World!"
android:layout_gravity="center_horizontal|center_vertical" />
</FrameLayout>
我的问题是,在活动启动时,我需要创建根视图的位图图像,但我不确定何时执行此操作可确保已膨胀根视图。