Android View getWidth方法始终返回0

时间:2013-12-12 17:26:11

标签: java android android-linearlayout android-gridview

我有一个GridView可以放入一些图像。我想要做的是对GridView进行测量,例如宽度和高度,以便我知道在getView()方法中显示图像时应该是最佳图像大小。我想每行只显示8个图像。因此,如果设备具有更大的屏幕,则图像将具有更大的尺寸,而不是通过为图像设置固定尺寸来在行中添加更多图像。

因此,在onCreate()方法中,我初始化自定义Adapter并将getWidthgetHeight值传递给它。但它们总是零。

在xml布局文件中,gridview是唯一的视图,然后我将它添加到linearlayout,所以它至少可以返回其父级的宽度和高度......但是它仍然为零。

以下是Activity的onCreate方法:

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_game);

    if (savedInstanceState == null) {
    }

    int difficulty = getIntent().getExtras()
            .getInt(AppConstants.EXTRAS_GAME_DIFFICULTY_LEVEL, 1);

    LinearLayout lvg = (LinearLayout) findViewById(R.id.linearForGridGame);
    GridView gv = (GridView) findViewById(R.id.gridview);

    gv.setAdapter(new CellAdapter(this, difficulty, lvg.getWidth(), lvg.getHeight()));

    gv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
        public void onItemClick(AdapterView<?> parent, View v, int position, long id) {
            Toast.makeText(GameActivity.this, "" + position, Toast.LENGTH_SHORT).show();
        }
    });
}

这是xml布局文件:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
    android:orientation="vertical"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/linearForGridGame">

<GridView xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/gridview"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:columnWidth="128px"
    android:numColumns="auto_fit"
    android:verticalSpacing="0dp"
    android:horizontalSpacing="0dp"
    android:stretchMode="none"
    android:gravity="center"
    android:choiceMode="none"
    android:listSelector="@null"
    android:clickable="true" />

    </LinearLayout>

这是适配器的cosntructor,我的宽度和高度始终为0:

public CellAdapter(Context context, int difficultyLevel,  int parentWidth, int parentHeight)
{
    _context = context;
    _dificultyLevel = difficultyLevel;
    _parentHight = parentHeight;
    _parentWidth = parentWidth;

    Log.d(TAG, "Received difficulty level " + _dificultyLevel); //OK
    Log.d(TAG, "Received parent width " + _parentWidth); //Always 0
    Log.d(TAG, "Received parent height " + _parentHight); //Always 0

    _cellWidth = (_parentWidth / 6); //Width of image to fill 6 per row
    setupGame(_dificultyLevel);
}

4 个答案:

答案 0 :(得分:2)

您必须等到视图层次结构膨胀并进行测量才能知道尺寸。在onCreate()

中添加类似的内容
    final ViewTreeObserver vto = lvg.getViewTreeObserver();
    vto.addOnGlobalLayoutListener(new OnGlobalLayoutListener() {

        @Override
        public void onGlobalLayout() {
            if (lvg.getWidth() > 10){ // because it may be called before the view is measured and you will still get 0
                // here you can get the measured dimensions
                ViewTreeObserver obs = pictureImg.getViewTreeObserver(); 
                obs.removeGlobalOnLayoutListener(this); // otherwise you're gonne keep getting called
            }
        }
    });

答案 1 :(得分:1)

尝试在活动的lvg.getWidth()中执行onWindowFocusChanged(boolean )

答案 2 :(得分:1)

我认为您必须使用 LayoutParams ,如下所示:

...
LinearLayout lvg = (LinearLayout) findViewById(R.id.linearForGridGame);
ViewGroup.LayoutParams layoutParams = lvg.getLayoutParams();
GridView gv = (GridView) findViewById(R.id.gridview);
gv.setAdapter(new CellAdapter(this, difficulty, layoutParams.getWidth(), layoutParams.getHeight()));
...

请务必导入 android.view.ViewGroup.LayoutParams

答案 3 :(得分:0)

onCreate()未发生视图布局,您可以通过继承View并观察何时调用onLayout()来自行查看。

this question中的大量信息。 ViewTreeObserver.OnGlobalLayoutListener可能比onWindowFocusChanged(boolean)更具体,因为您可以定位特定视图。

来自this answer的示例:

yourView.getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {

        @Override
        public void onGlobalLayout() {
            // Ensure you call it only once :
            yourView.getViewTreeObserver().removeGlobalOnLayoutListener(this);

            // Here you can get the size :)
        }
});