setContentView()
类中的Activity
方法的文档说明该视图已添加到活动窗口中并被夸大。但是,调用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>
我的问题是,我需要在活动启动时创建根视图的位图图像,但我不确定何时应该确保根视图已膨胀。
答案 0 :(得分:3)
正如@Onik正确评论的那样,他已经在Why does calling getWidth() on a View in onResume() return 0?
处回答了我的问题。我要补充一点,您还可以将addOnLayoutChangeListener
附加到视图并在onLayoutChange()
中将其删除。这很丑,但似乎是唯一的方法;