0

In my app I need to know what is the size of main container of activity. I have written following code:

Button btnActionMenu = (Button) findViewById(R.id.actionbar_menu);
        btnActionMenu.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                int width = (int)TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 40, getResources().getDisplayMetrics());
                RelativeLayout rlContainer = (RelativeLayout) findViewById(R.id.inner_content);
                Bitmap bitmap = Bitmap.createBitmap(rlContainer.getLayoutParams().width, rlContainer.getLayoutParams().height, Config.ARGB_8888);//
                Canvas canvas = new Canvas(bitmap);
                rlContainer.draw(canvas);
                SlideoutHelper.setBitmap(bitmap, width);
                startActivity(new Intent(Home.this, MenuActivity.class));
                overridePendingTransition(0, 0); 
            }
        });

rlContainer is the root container of activity. When I run and click on button, the application crashes and Logcat says "Application Null pointer exception" and points to line

Bitmap bitmap = Bitmap.createBitmap(rlContainer.getLayoutParams().width, rlContainer.getLayoutParams().height, Config.ARGB_8888);

any suggestion would be appreciated. Thanks

Hesam
  • 52,260
  • 74
  • 224
  • 365

2 Answers2

0

try this :

    v.measure(
    MeasureSpec.makeMeasureSpec(v.getLayoutParams().width,MeasureSpec.EXACTLY),
    MeasureSpec.makeMeasureSpec(v.getLayoutParams().height, MeasureSpec.EXACTLY));
    v.layout(0, 0, v.getMeasuredWidth(), v.getMeasuredHeight());
    Bitmap bitmap = Bitmap.createBitmap(v.getWidth(), v.getHeight()
   ,Bitmap.Config.RGB_565);
ρяσѕρєя K
  • 132,198
  • 53
  • 198
  • 213
0

have you tried getMeasuredHeight and getMeasuredWidth , or getHeight and getWidth (on the rlContainer variable ) ?

note that this works only after the view was prepared , and not inside the onCreate() method . however , it will work on this situation since it's inside a user-related action , which occurs after the views were shown to the user.

btw , about your code , "rlContainer.getLayoutParams().width" might return a negative value , in case it's wrap-content or match-parent .

android developer
  • 114,585
  • 152
  • 739
  • 1,270