2017-02-09 184 views
2

我试图在屏幕上显示一个Snackbar,其中一些文件数据在拍摄照片后在onActivityResult()方法中检索。getCurrentFocus()返回null

事情是,传递给Snackbar的查看返回null,我无法显示它。

这是onActivityResult()方法的代码:

@Override 
protected void onActivityResult(int requestCode, int resultCode, Intent data) { 
    super.onActivityResult(requestCode, resultCode, data); 

    if (requestCode == CAMERA_REQUEST_CODE && resultCode == RESULT_OK) { 
    File f = new File(mCurrentPhotoPath); 

    if (this.getCurrentFocus() != null) 
     Snackbar.make(this.getCurrentFocus(), f.length()/(1024 * 1024) + " MB, " + f.getPath(), Snackbar.LENGTH_INDEFINITE).show(); 
    } 
} 

任何想法,为什么出现这种情况?

谢谢!

回答

3

这是因为当您调用另一个Activity时,当前焦点在调用者Activity中丢失,因此它被设置为null。

由于documentation says

查看getCurrentFocus()

返回在此窗口that currently has focus视图,则返回null 有没有。请注意,这不包含任何包含窗口。

您可以用活动的根视图为小吃吧

// Get the root current view. 
View view = findViewById(android.R.id.content); 
Snackbar.make(view, f.length()/(1024 * 1024) + " MB, " + f.getPath(), Snackbar.LENGTH_INDEFINITE).show(); 

UPDATE

请注意,

findViewById(android.R.id.content); 

可能在某些设备上位于导航栏后面(带有后退按钮等)(但在大多数设备上似乎不是这样)。 正如https://stackoverflow.com/a/4488149/4758255所说。

你可以使用:

final ViewGroup viewGroup = (ViewGroup) ((ViewGroup) this 
      .findViewById(android.R.id.content)).getChildAt(0); 

不过还好只是设置ID这一观点在XML布局,并使用这个号码来代替。

或者作为运说,我们可以使用:

View v1 = getWindow().getDecorView().getRootView(); 
+0

感谢您的答案!对不起,迟到的回应,我找到了另一个解决方案。 'View v = getWindow()。getDecorView()。getRootView();'这样我就可以获得Activity的根视图并将其作为Snackbar.make()方法中的第一个参数传递给 –

+0

没问题。我已将您的解决方案集成到我的答案中。如果有人遇到同样的问题。 –

0

您可以在活动中使用getCurrentFocus()的视图。你几乎总会看到一个观点。它是可空的