Friday, December 21, 2012

How to change layout size (and other parameters) in code

It is really easy to change layout parameters, but you have to pay attention here: I'm changing LinearLayout, but parent of this layout - RelativeLayout. So I have to set LayoutParams for RelativeLayout otherwise I'll get ClassCastException.
LinearLayout layout = (LinearLayout)findViewById(R.id.activity_layout);
layout.setLayoutParams(new RelativeLayout.LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.WRAP_CONTENT));

Easy way to check if soft keyboard is open

Here's the really easy way to handle very specific 'soft' keyboard events: opening and closing.
final RelativeLayout view = (RelativeLayout)findViewById(R.id.activity_loading);
view.getViewTreeObserver().addOnGlobalLayoutListener(new OnGlobalLayoutListener() {
    @Override
        public void onGlobalLayout() {
            if ((view.getRootView().getHeight() - view.getHeight()) >    
                    view.getRootView().getHeight()/3) {
            
  // keyboard is open

            } else {
             
  // keyboard is closed
            
     }
        }
    });