Android 屏幕方向改变

标签 android

我正在制作一个程序,当我按下按钮时,它会更改背景颜色,但我有一个问题,当我更改屏幕方向时,它会再次将颜色更改为预定义的颜色,我不知道如何解决这个问题...这是我的代码。

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);

    }

    }    

最佳答案

问题是当方向改变时, Activity 会重新启动。有多种方法可以解决这个问题。

一种方法是使 Activity 在方向更改时不会重新启动。操作方法如下:

添加android:configChanges="orientation|screenSize"给您<activity标签,位于您的 AndroidManifest.xml 中,像这样:

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

Rastikan's answer做法略有不同,但他的做法不适用于 API 12 之后的任何 API( sourcethis too )。按照我上面的方式,您实际上不需要调用 onConfiguationChanged在您的 Activity 类(class)中。

另一种方法是使用 onSaveInstanceState(Bundle savedInstanceState)Rastikan做到了。

另一种方法是让 Activity 自行重新启动,然后使用 onResume()如有必要,当 Activity 重新启动时更改背景颜色的方法。像这样:

public boolean changeColor = false;

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

public void onResume()
{
    if (changeColor) {
        // change the background color
    }
}

关于Android 屏幕方向改变,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20306809/

相关文章:

javascript - 我正在尝试用 jQuery 替换 Xpath

android - 当按下主页按钮时,服务仍然绑定(bind)到主要 Activity ,当查看不同的 Activity 时

android - 在 Android 中显示屏幕底部的 TextView

java - UI 线程等待其他线程执行 - 不工作

android - 设置蓝牙信标设备的 UUID 无法正常工作

android - 使用 Objective C 进行 iOS 开发的 RxJava 和日志

android - 在android webview中添加自定义进度条

Android 资源限定符 -sw#dp 与 -w#dp

android - GooglePlay 表示设备不兼容,但开发者控制台将其显示为兼容

android - 双变量格式