Edit: I'm trying to get the height/width of a view, so that I can programmatically put some ImageView
into it. However getHeight()
and getWidth()
returns 0 so I was not able to put the ImageView
into the correct positions. I did make the ImageView
appear on the RelativeView
(main_activity
) though.
I'm aware of the answer related the getHeight()
returning 0
error: How to retrieve the dimensions of a view?
Unfortunately it's gives me exception on the line with ld.setLayerInset()
, saying I'm trying to invoke the method on a null pointer reference. I' aware of the meaning of such an exception, but I don't understand what's wrong with my code as I was just trying to copy and paste the codes on the above link to my codes with amendments on the variable names. Here are some of my codes:
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
findViewById(R.id.activity_main).getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
public void onGlobalLayout() {
LayerDrawable ld = (LayerDrawable) findViewById(R.id.activity_main).getBackground();
ld.setLayerInset(1,0,0,0,0);
if (Build.VERSION.SDK_INT >= 16) {
findViewById(R.id.activity_main).getViewTreeObserver().removeOnGlobalLayoutListener(this);
} else {
findViewById(R.id.activity_main).getViewTreeObserver().removeGlobalOnLayoutListener(this);
}
}
});
...
}
I think the problem occurs on getBackground()
getting null
then cause the next line to throw exception, but I don't know what's the problem at all.