Android - Global Layout Listener not working

我怕爱的太早我们不能终老 提交于 2019-12-09 12:11:44

问题


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);
        }
     }
});

回答1:


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);
                }
             }
        });
    }
}


来源:https://stackoverflow.com/questions/14298458/android-global-layout-listener-not-working

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!