Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

getCurrentFocus() returns null

I'm trying to display a Snackbar in the screen with some File data that I retrieve in the onActivityResult() method after taking a photo.

The thing is that the View that is passed to the Snackbar returns null and I cannot display it.

This is the code of the onActivityResult() method:

@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();
  }
}

Any idea why this happen?

Thanks!

like image 854
Iván Guerra Avatar asked Feb 09 '17 00:02

Iván Guerra


1 Answers

This is because when you calling another Activity, the current focus is lost in the caller Activity so it's set to null.

As the documentation says:

View getCurrentFocus ()

Return the view in this Window that currently has focus, or null if there are none. Note that this does not look in any containing Window.

You can use the root view of your activity for the 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

Please be noted that

findViewById(android.R.id.content);

may be behind navigation bar (with back button etc.) on some devices (but it seems on most devices it is not). As in the https://stackoverflow.com/a/4488149/4758255 says.

you can use:

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

But better just set id to this view in your xml layout and use this id instead.

Or as op has said, we can use:

View v1 = getWindow().getDecorView().getRootView();
like image 155
ישו אוהב אותך Avatar answered Nov 03 '22 07:11

ישו אוהב אותך