Android:以编程方式在自定义视图中设置match_parent

时间:2015-04-27 20:29:33

标签: android custom-view onmeasure

我实现了一个可以绘制的自定义视图。我想将它设置为MATCH_PARENT,以便它独立于屏幕方向填充屏幕。当我将方向更改为横向时,它只会填充宽度的50%。

我改变了onMeasure(),但没有效果:

public class DrawScreen extends View{

@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
    super.onMeasure(widthMeasureSpec, heightMeasureSpec);   
    if(context.getResources().getConfiguration().orientation==Configuration.ORIENTATION_LANDSCAPE){
        setMeasuredDimension(screenWidth, screenHeight);
    }else{
        setMeasuredDimension(screenHeight, screenWidth);
    }

}
}


public class MyService extends Service{

...
windowManager.addView(toolbox, params);
}

1 个答案:

答案 0 :(得分:2)

您可以尝试以下方法:

final DrawScreen view = new DrawScreen(...);
final LayoutParams lp = new LayoutParams(MATCH_PARENT, MATCH_PARENT);
view.setLayoutParams(lp);