2

I'm making a program that when I press a button this change the background color but I have a problem with, when I change the screen orientation this change again the color to the predefined and I dont know how to solve this problem... Here is my code.

public class MainActivity extends Activity implements OnClickListener {

    LinearLayout myLayout;
    LinearLayout myLayout2;

    // Declare UI elements
    private Button firstButton, secondButton, thirdButton, fourthButton, fifthButton;

    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main); // Our only layout for this app is main.xml

        myLayout = (LinearLayout) findViewById(R.id.myLayout);
        myLayout2 = (LinearLayout) findViewById(R.id.myLayout2);

        // Initialize the UI components

        firstButton = (Button) findViewById(R.id.button1); 
        // When we creating a button and if we expect that to use for event handling we have to set the listener
        firstButton.setOnClickListener(this);
        secondButton = (Button) findViewById(R.id.button2);
        secondButton.setOnClickListener(this);
        thirdButton = (Button) findViewById(R.id.button3);
        thirdButton.setOnClickListener(this);
        fourthButton = (Button) findViewById(R.id.button4);
        fourthButton.setOnClickListener(this);
        fifthButton = (Button) findViewById(R.id.button5);
        fifthButton.setOnClickListener(this);

    }

    }    
jaimito
  • 135
  • 2
  • 12

2 Answers2

3

The problem is that when the orientation is changed, the activity is restarted. There are multiple ways to fix that.

One way is to make it so that the activity won't restart when the orientation is changed. Here's how to do that:

Add android:configChanges="orientation|screenSize" to your <activity tag, which is in your AndroidManifest.xml, like so:

<activity
    android:name="UserIdActivity"
    android:label="@string/app_name"
    android:configChanges="orientation|screenSize" />

Rastikan's answer did it slightly differently, but his way of doing it won't work for any API after API 12 (source and this too). My way above, you don't actually need to call onConfiguationChanged in your activity class.

Another way of doing it would to use onSaveInstanceState(Bundle savedInstanceState) like Rastikan did.

Another way of doing it would be to let the activity restart itself, but then using the onResume() method to change the background colour, if necessary, when the activity is restarted. Like this:

public boolean changeColor = false;

// set changeColor to be true whenever you change the background colour

public void onResume()
{
    if (changeColor) {
        // change the background color
    }
}
Community
  • 1
  • 1
Michael Yaworski
  • 13,410
  • 19
  • 69
  • 97
  • I'm adding the line you have said but doesnt work... – jaimito Dec 01 '13 at 09:16
  • @user2958480 put the line in your AndroidManifest.xml instead. Sorry, I forgot to mention that originally. – Michael Yaworski Dec 01 '13 at 09:32
  • still not working... – jaimito Dec 01 '13 at 09:50
  • @user2958480 what do you mean by "not working"? it is changing the colour back whenever you rotate it still? take out all of the other stuff with `onSavedInstanceState` and `onResume()` and whatever else. Also, make sure that you're putting the line of code in the proper activity. Do you have multiple activities in your code? – Michael Yaworski Dec 01 '13 at 09:57
  • I have add the part of my manifest... and my code looks as well as I have posted... – jaimito Dec 01 '13 at 13:33
  • @jaimito Ok, go to this website: http://pastie.org and paste your entire MainActivity class AND your manifest into the text box, select Java for the language (top right of the the text box) and then click create paste. Then send me the link. Also, please upvote my answer. – Michael Yaworski Dec 01 '13 at 18:49
  • Sure! Done, and One more question... as you can see I'm using 5 buttons to set the background in different colours and I want to add a menu before start to use this buttons, what I want to do it's trying to show now an option which mode it will start with (with or without buttons) in the same app, I know I have to use getPreferences() but I dont know how to implement this now.. do you have any idea? – jaimito Dec 01 '13 at 20:40
  • @jaimito These links should help you use preferences, and the option menu: http://stackoverflow.com/questions/19353758/how-to-save-app-settings/19353944#19353944 and http://stackoverflow.com/questions/18521225/how-to-manipulate-the-activitys-options-menu . Also, please vote up the questions/answers that help you with your problem. If those resources don't specifically help you, Google "how to use android options menu" and "how to use shared preferences android", etc. – Michael Yaworski Dec 01 '13 at 20:48
-1

Here is a short/alternate version assuming a view (view1) of some sort.

import android.os.Bundle;
import android.app.Activity;
import android.graphics.Color;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;

public class MainActivity extends Activity {

    private static final int DEFAULT_COLOR = Color.WHITE;

    private int myColor;
    // Assuming a 'view' of some sort
    private View myView;

    // Declare UI elements
    private Button firstButton;

    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main); // Our only layout for this app
                                                // is main.xml

        myView      = (View)   findViewById( R.id.view1   );
        firstButton = (Button) findViewById( R.id.button1 );

        Log.i("MainActivity", "onCreate"
                + ((null == savedInstanceState) ? "(null)"
                        : "(savedInstanceState)"));

        if (savedInstanceState != null) {
            myColor = savedInstanceState.getInt("COLOR");
        } else {
            myColor = DEFAULT_COLOR;
        }

        myView.setBackgroundColor(myColor);

        firstButton.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                if (myColor == Color.WHITE)
                    myColor = Color.BLACK;
                else if (myColor == Color.BLACK)
                    myColor = Color.WHITE;

                myView.setBackgroundColor(myColor);
            }

        });
    }

    @Override
    // this method is called before android trashes and recreates your activity
    protected void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
        outState.putInt("COLOR", myColor);
    }
}

Alternatively you could do it the cheap-dumb-ass way: Locking the screen. add the 'android:configChanges' attribute to your activity.

 <activity
    android:name="UserIdActivity"
    android:label="@string/app_name"
    android:configChanges="orientation" />

And implement the 'onConfigurationChanged' callback to do nothing

public void onConfigurationChanged ( Configuration newConfig)
{
}
Rastikan
  • 517
  • 5
  • 18
  • "Alternatively you could do it the cheap-dumb-ass way". It's not the cheap, or dumbass way. That prevents the activity from being destroyed, your first method didn't. There are pros/cons to both. – Michael Yaworski Dec 01 '13 at 01:19
  • You are right Mike, my english is not so good. Anyway, I often have to implement some acitvities that way ( actually adding the slew conditions 'orientation|keyboardHidden|keyboard|touchscreen|screenLayout|screenSize|uiMode' ) because we don't want an active BT connection being interrupted ... at least until someone have an hour or two updating the Bluetooth code to be a service. – Rastikan Dec 01 '13 at 02:29