我试图在屏幕上显示 Snackbar ,其中包含我在拍摄照片后在onActivityResult()
方法中检索的一些文件数据。
问题是传递给Snackbar的 View 返回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();
}
}
知道为什么会这样吗?
谢谢!
答案 0 :(得分:5)
这是因为当你调用另一个Activity时,当前焦点会在调用者Activity中丢失,因此它被设置为null。
查看getCurrentFocus()
返回此窗口中的视图
that currently has focus
,如果是,则返回null 没有了。请注意,这不包含任何包含Window的内容。
您可以将活动的根视图用于 Snackbar :
// 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();
<强>更新强>
请注意
findViewById(android.R.id.content);
可能在某些设备上的导航栏(带后退按钮等)后面(但在大多数设备上似乎不是这样)。 正如在https://stackoverflow.com/a/4488149/4758255中说的那样。
你可以使用:
final ViewGroup viewGroup = (ViewGroup) ((ViewGroup) this
.findViewById(android.R.id.content)).getChildAt(0);
但最好只在xml布局中为此视图设置id并改为使用此ID。
或者正如op所说,我们可以使用:
View v1 = getWindow().getDecorView().getRootView();
答案 1 :(得分:0)
您可以使用getCurrentFocus()
查看活动中的视图。你几乎总能得到一个观点。它是可以为空的