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

6
我使用了Reuben Scratton在这个问题中的新答案。当我将其粘贴到我的代码中时,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);
        }
     }
});

17
请不要试图通过复制/粘贴来学习Java和Android编程。这不是一个成功的方法。从基础开始,从“Hello World”开始。 - Simon
1个回答

19

你需要将该代码放在一个方法中,例如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);
                }
             }
        });
    }
}

这么简单的修复。对我有用。谢谢! - Eichhörnchen
@Sam,我给你点赞,这对我很有帮助。 - Pratik Sharma
2
在我的项目中,onGlobalLayout 在一个普通类的方法中被调用,而这个方法在一个 fragment 的 onCreate 方法中被调用。我的问题是,在调试应用程序时,onGlobalLayout 下的代码块是无法到达的。 - Fakher
如果我在使用数据绑定呢?@Sam - Dr4ke the b4dass
@Dr4ketheb4dass 你可以调用绑定组件的getRoot()方法来获取布局的根视图。 - vilpe89

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接