Android - 全局布局监听器无法正常工作

Eic*_*hen 6 layout android listener android-softkeyboard

我在这个问题中使用了Reuben Scratton的新答案代码.当我把它贴到我的代码,我得到红squigglies下 addOnGlobalLayoutListener(new OnGlobalLayoutListener(),onGlobalLayout()activityRootView(heightDiff后).请帮我弄清楚出了什么问题.

谢谢这是我在.java页面上的代码

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);
        }
     }
});
Run Code Online (Sandbox Code Playgroud)

Sam*_*Sam 16

您需要在方法中添加该代码,例如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);
                }
             }
        });
    }
}
Run Code Online (Sandbox Code Playgroud)

  • 在我的项目中,在普通类的方法中调用onGlobalLayout,并且在片段中的onCreate方法中调用此方法,我的问题是当我调试应用程序时,onGlobalLayout下的代码块无法访问. (2认同)