Pergunta

How can I set an GestureOverlayView's width and height programmatically?

I tried the below code. But I am getting null pointer exception in setting the width and height.

    GestureOverlayView gestureOverlayView = new GestureOverlayView(this);
    View inflate = getLayoutInflater().inflate(R.layout.main, null);
    ImageView imageView = (ImageView) inflate.findViewById(R.id.imageView);
    gestureOverlayView.addView(inflate);
    gestureOverlayView.getLayoutParams().height = 50;
    gestureOverlayView.getLayoutParams().width = 50;
    setContentView(gestureOverlayView);
Foi útil?

Solução

You need to add the view first before you can read out the height and width. Also then you meight get some trouble only after the second or third call of onMeasure(...) the dimensions are final.

If you want to set the width and height by code use this:

ViewGroup.LayoutParams lp = gestureOverlayView.getLayoutParams();
if(lp == null) {
    // not yet added to parent
    lp = new ViewGroup.LayoutParams(desiredWidth, desiredHeight);
} else {
    lp.width = desiredWidth;
    lp.height = desiredHeight;
}
gestureOverlayView.setLayoutParams(lp);

yourparent.addView(gestureOverlayView, lp);

Please note that you need to choose also the right LayoutParams implementation. Here I use that one of ViewGroup.

Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top