问题描述
我正在尝试在屏幕上显示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();
}
}
知道为什么会这样吗?
谢谢!
1楼
这是因为当您调用另一个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();
UPDATE
请注意
findViewById(android.R.id.content);
可能在某些设备上的导航栏(带后退按钮等)后面(但在大多数设备上似乎不是这样)。 如在中所述。
您可以使用:
final ViewGroup viewGroup = (ViewGroup) ((ViewGroup) this
.findViewById(android.R.id.content)).getChildAt(0);
但最好只在xml布局中将id设置为此视图并改为使用此id。
或者如op所说,我们可以使用:
View v1 = getWindow().getDecorView().getRootView();
2楼
您可以使用getCurrentFocus()
在活动中进行查看。
你几乎总能得到一个观点。
但它可以为空