简体   繁体   English

方向更改后无法设置Button的ImageResource

[英]Unable to set ImageResource of Button after orientation change

the aim is to change the image resource of the button. 目的是改变按钮的图像资源。 If I don't change the orientation it works correctly, but if I change the orientation, the image resource is not set (or probably not updated). 如果我不更改方向它可以正常工作,但如果我更改方向,图像资源不会设置(或可能不更新)。 I observe in DebugMode that the following code (toggleButton method) is always executed, regardless the screen orientation is changed. 我在DebugMode中观察到,无论屏幕方向是否改变,总是执行以下代码(toggleButton方法)。 The buttonIconID is also always correct. buttonIconID也始终正确。 The problem is, that the image resource of the button is not set after changing the orientation. 问题是,在更改方向后未设置按钮的图像资源。

@Override
public void onCreate(Bundle savedInstanceState) {
    ...
    mTopBar = new TopBar(this);
    ...
}

TopBar constructor: TopBar构造函数:

public TopBar(MainActivity mainActivity) {
    this.mainActivity = mainActivity;

    mButton = (ImageButton) mainActivity
            .findViewById(R.id.toggleButton);
    mButton.setOnTouchListener(this);
    ...
}

toggleButton method in TopBar: TopBar中的toggleButton方法:

public void toggleButton(final int buttonIconID) {
    mainActivity.runOnUiThread(new Runnable() {

        @Override
        public void run() {
                mButton.setImageResource(buttonIconID);
        }
    });
}

Thanks for your help! 谢谢你的帮助!

An Activity is recreated every time you change the orientation. 每次更改方向时都会重新创建Activity So when you change the orientation all views are reseted to their standard configuration (or the settings you have set in the onCreate() / onResume() etc methods. 因此,当您更改方向时,所有视图都将重置为其标准配置(或您在onCreate() / onResume()等方法中设置的设置。

So if you want to keep the image resource you have set programmatically after changing the orientation, you should buffer the data and set it again in the onCreate() or onResume() method. 因此,如果要保留在更改方向后以编程方式设置的图像资源,则应缓冲数据并在onCreate()onResume()方法中再次设置。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM