我有一个ViewAnimator,它的view0是一个TableLayout,主要由可点击的ImageViews行组成,它的视图是一个欢迎屏幕。当应用程序被创建时,它不仅需要填充ImageViews动态地(因为它必须知道每个元素有多大),但它做了相当多的数字运算那么,我想隐藏TableLayout,直到它准备好进行交互。然而,当我视图1在onCreate()中可见,应用程序随后抛出异常,因为它认为ImageView有宽度高度为0
是否有一种方法可以动态地初始化一个视图,而另一个视图在前台,没有在XML中硬编码ImageView的大小(我真的不能这样做,因为它取决于大小)屏幕)?
下面是主XML的相关部分:
<ViewAnimator xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/MainView"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
tools:context=".MainActivity">
<TableLayout android:id="@+id/TheGridView"
android:layout_width="match_parent"
android:layout_height="match_parent">
<TableRow
android:layout_width="match_parent"
android:layout_height="0dip"
android:layout_weight="1">
<ImageView android:id="@+id/TheImageView"
android:tag="tag_TheImageView"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_weight="1"
android:gravity="center"
android:background="#FF0"
android:clickable="true"
android:onClick="TheImageView_Clicked"
android:layout_margin="2dip"
android:contentDescription="@string/TheImageView"
下面是MainActivity.java中导致问题的代码(它是在onCreate()调用的方法中):
TableLayout ScreenLayout = (TableLayout)findViewById(R.id.TheGridView);
ImageView V = (ImageView)ScreenLayout.findViewWithTag("tag_TheImageView");
int ButtonWidth = V.getWidth();
int ButtonHeight = V.getHeight();
Bitmap ButtonBitmap = Bitmap.createBitmap(ButtonWidth, ButtonHeight, Config.ARGB_8888);
注意,将TableRow的layout_height值更改为> 0没有影响-它仍然认为大小为0 x 0。
这是因为imageview的宽度和高度实际上是零,当onCreate执行时,还没有任何可见或绘制。你必须把代码放在onWindowFocusChanged生命周期方法