6

我在这个问题中使用了 Reuben Scratton 的新答案中的代码。当我将它粘贴到我的代码中时,我会在 、 和 (在 heightDiff 之后)下面看到红色的 addOnGlobalLayoutListener(new OnGlobalLayoutListener()波浪onGlobalLayout()线activityRootView。请帮我找出问题所在。

谢谢这是我在.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);
        }
     }
});
4

1 回答 1

17

您需要在方法中添加该代码,例如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);
                }
             }
        });
    }
}
于 2013-01-12T22:15:08.123 回答