Android - global layout receiver 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 under addOnGlobalLayoutListener(new OnGlobalLayoutListener() , onGlobalLayout() and activityRootView (after heightDiff). Please help me find out what is wrong.

Thank you. Here is 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); } } }); 
+6
source share
1 answer

You need to add this code inside the method, for example 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); } } }); } } 
+14
source

All Articles