Seth
Seth

Reputation: 1

Track Orientation Changes without using onConfigurationChanged()

I have been working on an assignment that simply displays a text field counting the number of time orientation changed as shown below.

What i'm trying to accomplish with the app:

The problem the above app's code is using onConfigurationChanged(), and I believe we are not suppose to bypass the activity lifecycle, but I cannot find a way to listen for an orientation change and increment a counter.

   public void onConfigurationChanged(Configuration newConfig) {
    super.onConfigurationChanged(newConfig);
    Log.i(TAG, "ORIENTATION HAS CHANGED");
    mCurrentIndex++;
    TextView text= (TextView) findViewById(R.id.myTextView);
    text.setText("Orientation changes: " + oChanges());
}

Is currently what im using because if I put mCurrentIndex, which is my counter, in a lifecycle method like onPause() it will also be called if you went to the homescreen or anything like that.

Upvotes: 0

Views: 77

Answers (1)

Gabe Sechan
Gabe Sechan

Reputation: 93589

Doing onConfigurationChanged is the right method. You can do it in another way, but its a lot of work. In onSaveInstanceState, write the current orientation and value of the counter. In onRestoreInstanceState, read both in. If the new orientation does not match the old orientation, increment the counter after reading it in.

Upvotes: 2

Related Questions