I have made a simple example to ilustrate the problem. Here is a simple LinearLayout:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/ll"
android:orientation="horizontal"
android:layout_width="fill_parent"
android:layout_height="fill_parent">
</LinearLayout>
and then I populate it in onCreate()
private final String TAG = getClas开发者_JAVA技巧s().getSimpleName();
ImageView iv1;
ImageView iv2;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
LinearLayout container = (LinearLayout) findViewById(R.id.ll);
LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT);
lp.weight=1.0f;
iv1 = new ImageView(this);
iv1.setImageResource(R.drawable.icon);
iv2 = new ImageView(this);
iv2.setImageResource(R.drawable.icon);
container.addView(iv1, lp);
container.addView(iv2, lp);
container.measure(LinearLayout.LayoutParams.FILL_PARENT, LinearLayout.LayoutParams.FILL_PARENT);
Log.d(TAG, " measured width(1): " + iv1.getMeasuredWidth());
Log.d(TAG, " measured width(2): " + iv2.getMeasuredWidth());
where icon is a simple image of 48x48dp. question is: why getMeasuredWidth returns 48 in Logs, but when i look in hierarchy viewer mMeasureWidth is 160? In other words the real question is .. how can I get real width/height (in Java) of the view when it is stretched in a LinearLayout ? Calling requestLayout(), measure() does not work. I could try to get a sum of weigths and calculate everything that LinearLayout does, but maybe there is a more elegant solution.
onCreate is called much before the activity is displayed.
Therefore, iv1.getMeasuredWidth() is not yet the value you expect and should be called in another method, later. I think onWindowFocusChange is correct.
精彩评论