Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Android - Global Layout Listener not working

I used the code from Reuben Scratton's new answer in this question. When I paste it into my code, I get red squigglies underneath addOnGlobalLayoutListener(new OnGlobalLayoutListener(), onGlobalLayout(), and activityRootView (after heightDiff). Please help me figure out what is wrong.

Thanks Here's my code on the .java page

public class Details extends Activity {

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    this.requestWindowFeature(Window.FEATURE_NO_TITLE);
    setContentView(R.layout.activity_details);
    Intent intent = getIntent();        
}


final View activityRootView = findViewById(R.id.details);
activityRootView.getViewTreeObserver().addOnGlobalLayoutListener(new OnGlobalLayoutListener() {

    @Override
    public void onGlobalLayout() {
        int heightDiff = activityRootView.getRootView().getHeight() - activityRootView.getHeight();
        if (heightDiff > 100) { // if more than 100 pixels, its probably a keyboard...
            ImageButton backButton = (ImageButton)findViewById(R.id.back); 
            backButton.setImageResource(R.drawable.hide_keyboard);
        }
     }
});
like image 741
Eichhörnchen Avatar asked Jan 12 '13 22:01

Eichhörnchen


1 Answers

You need to add that code inside a method, like onCreate().

public class Details extends Activity {
    View activityRootView;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        this.requestWindowFeature(Window.FEATURE_NO_TITLE);
        setContentView(R.layout.activity_details);
        Intent intent = getIntent();        

        activityRootView = findViewById(R.id.details);    
        activityRootView.getViewTreeObserver().addOnGlobalLayoutListener(new OnGlobalLayoutListener() {
            @Override
            public void onGlobalLayout() {
                int heightDiff = activityRootView.getRootView().getHeight() - activityRootView.getHeight();
                if (heightDiff > 100) { // if more than 100 pixels, its probably a keyboard...
                    ImageButton backButton = (ImageButton)findViewById(R.id.back); 
                    backButton.setImageResource(R.drawable.hide_keyboard);
                }
             }
        });
    }
}
like image 57
Sam Avatar answered Oct 06 '22 21:10

Sam