In an Activity
, I am manually inflating a View
object from XML as follows:
LayoutInflater inflater = LayoutInflater.from (this);
View topView = inflater.inflate (R.layout.topview_layout, null);
I won't be adding the view to any display hierarchy, but rather using it to generate bitmaps which I will then display. Since those bitmaps will be the size of my (main) screen, I try to cause the layout to occur:
Display display = ((WindowManager) getSystemService (Context.WINDOW_SERVICE))
.getDefaultDisplay();
topView.measure (display.getWidth (), display.getHeight ());
topView.layout (0, 0, display.getWidth (), display.getHeight ());
(It is getting the proper size of the display in the above code.)
topView
is a LinearLayout
开发者_如何学C which contains a few other views. One of them is an ImageView
:
ImageView childView = (ImageView) pageView.findViewById (R.id.textArea);
However, this view never seems to be informed about its dimensions after the call to layout()
:
int childViewWidth = childView.getWidth ();
int childViewHeight = childView.getHeight ();
(The dimensions retrieved by the above code are 0,0.)
All of the above code occurs linearly, and is called from within my Activity subclass' onCreate()
method.
The layout XML I'm testing with is:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/topView"
android:orientation="vertical"
android:background="@color/blue"
android:layout_width="match_parent"
android:layout_height="match_parent">
<ImageView
android:id="@+id/textArea"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="@color/gold"/>
</LinearLayout>
I would most appreciate any clues!
NOTE: Edited to add the layout XML and the measure()
call pointed out as missing by Romain Guy.
You need to call measure() before you call layout().
First thing is inflate won't consider the layout parameters that you have specified in the xml. You can fix that by using
inflater.inflate( R.layout.top_view_layout /* resource id */, parentView, false /* attachToRoot */);
This will make sure that you are using the match_parent for both width and height.
OR
If you don't want to do that, then you should set the LayoutParams for the inflated view first.
P.S.: AFAIK, the layout method will take the parameters which are screen area available for display (left, top, right, bottom), but it will consider original size of the view for displaying (which is 0,0 in your case).
精彩评论