如何使用RelativeLayout.LayoutParams将subView添加到ViewGroup

时间:2013-01-22 09:06:54

标签: android viewgroup

我编写了一个扩展ViewGroup的类,并覆盖了以下方法:

 @Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        super.onMeasure(widthMeasureSpec, heightMeasureSpec);
    for(int index = 0; index < getChildCount(); index++){
            int width = MeasureSpec.getSize(widthMeasureSpec);
            int height = MeasureSpec.getSize(heightMeasureSpec);
            View child = getChildAt(index);
            child.measure(View.MeasureSpec.makeMeasureSpec(width,
                    View.MeasureSpec.UNSPECIFIED), View.MeasureSpec
                    .makeMeasureSpec(height, View.MeasureSpec.UNSPECIFIED));
    }
}

当我将subView添加到此viewGroup时,如下所示:

String word = words[random.nextInt(words.length)];
            RelativeLayout layout = new RelativeLayout(DraggableGridViewSampleActivity.this);
            TextView text = new TextView(DraggableGridViewSampleActivity.this);
            text.setText(word);
            ImageView view = new ImageView(DraggableGridViewSampleActivity.this);
            view.setImageBitmap(getThumb(word));
            layout.addView(view);

            RelativeLayout.LayoutParams params = new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.FILL_PARENT, RelativeLayout.LayoutParams.WRAP_CONTENT);
            params.addRule(RelativeLayout.ALIGN_PARENT_RIGHT);
            layout.addView(text, params);
            dgv.addView(layout);

效果如下:textView无法完全显示。看起来父视图没有为textview显示提供足够的空间。

如何完整显示textView?

1 个答案:

答案 0 :(得分:0)

  

无法完全显示textView。看来是父母   视图没有为textview显示提供足够的空间。

您到底想用onMeasure方法做什么?现在你让超类处理孩子的初始测量(super.onMeasure),然后再次测量孩子,这次给他们一个MeasureSpec.UNSPECIFIED,基本上告诉孩子他们可能是他们想要的大。

当你测量孩子时(或者父母应该允许滚动),你应该始终尊重MeasureSpec。如果家长说儿童应该AT_MOST 500像素,那么在衡量儿童时,不要给他们MeasureSpec UNSPECIFIED {。}}。