【问题标题】:Android - Global Layout Listener not workingAndroid - 全局布局侦听器不起作用
【发布时间】:2013-01-12 22:11:42
【问题描述】:

我在this question 中使用了 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);
        }
     }
});

【问题讨论】:

  • 请不要试图通过复制/粘贴来学习Java和Android编程。这不是一个成功的方法。浏览基础知识并从“Hello World”开始

标签: android layout listener android-softkeyboard


【解决方案1】:

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

【讨论】:

  • 如此简单的修复。为我工作。谢谢!
  • @Sam +1 来自我,这对我很有帮助。
  • 在我的项目中,onGlobalLayout在普通类的方法中被调用,而这个方法在片段的onCreate方法中被调用,我的问题是当我调试应用程序时,代码块onGlobalLayout 下无法访问。
  • 如果我使用数据绑定怎么办? @山姆
猜你喜欢
  • 1970-01-01
  • 2017-08-27
  • 2015-10-21
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-08-28
  • 2015-05-11
  • 1970-01-01
相关资源
最近更新 更多