문제

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);
도움이 되었습니까?

해결책

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.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top