ACP Daya
ACP Daya

Reputation: 71

onWindowFocusChanged not work in Lollipop?

I'm trying to use the onWindowFocusChanged in application but they not support to lollipop.

@Override
public void onWindowFocusChanged(boolean hasFocus) {

    super.onWindowFocusChanged(hasFocus);
    Log.e(TAG, "onWindowFocusChanged, " + hasFocus);
    mWindowhasFocus = hasFocus;

}

Upvotes: 1

Views: 1619

Answers (1)

Konstantin Loginov
Konstantin Loginov

Reputation: 16000

No, it's actually working on Lollipop (and even on Marshmallow - I checked).

The documentation about this method says:

Called when the current Window of the activity gains or loses focus. This is the best indicator of whether this activity is visible to the user. The default implementation clears the key tracking state, so should always be called.

I wrote very simple one-Activity-test app: MainActivity.java

public class MainActivity extends AppCompatActivity {

    TextView statusTextView;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        statusTextView = (TextView)findViewById(R.id.statusTextView);
    }

    @Override
    public void onWindowFocusChanged(boolean hasFocus) {
        super.onWindowFocusChanged(hasFocus);
        String newStatus = statusTextView.getText() + (hasFocus? "Got focus" : "Lost focus") + "\n";
        statusTextView.setText(newStatus);
    }
}

activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:padding="16dp">
    <TextView
        android:id="@+id/statusTextView"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content" />
</RelativeLayout>

So by moving app to the background back and forth, you can see how the state is changing.

Upvotes: 1

Related Questions