繁体   English   中英

如何在onRestoreInstanceState()中设置视图的背景色

[英]How to set the Background Color of a View in onRestoreInstanceState()

我目前正在尝试学习使用视图和状态。 通常,我可以在如下函数中设置其颜色:

    View mColorRegion = findViewById(R.id.color_region);
    mColorRegion.setBackgroundColor(Color.CYAN);

但是,我似乎无法在onRestoreInstanceState()中设置颜色,因为

     mColorRegion.setBackgroundColor(savedInstanceState.getInt("color"));

但是,使用与TextView相同的View,我可以按照以下方式还原文本:

    TextView mText = (TextView)findViewById(R.id.color_region);
    mText.setText(savedInstanceState.getString("text");

有什么区别,以及如何在onRestoreInstanceState()中设置背景颜色?



编辑:自原始帖子以来,我注意到两件事:


1) mColorRegion.setBackgroundColor(Color.CYAN)似乎在onCreate()中也不起作用。

2)即使下面的函数在按下按钮时可以正确更改“视图”颜色,但是如果我直接从onRestoreInstanceState()调用它,它将无法正常工作:

    public void centerButton1(View clickedButton) {
        mColorRegion.setBackgroundColor(Color.CYAN);
    }

嗯...

所以我找到了一个“半解”。 如果将以下行添加到AndroidManifest.xml ,它将在方向更改时保留颜色:

     android:configChanges="orientation|screenSize"


但是,这仍然不能回答为什么我可以在onRetoreInstanceState()onCreate()中设置文本但不能设置颜色的原因 ...

许多人不喜欢使用android:configChanges="orientation|screenSize" ,例如Google的Dianne Hackborn 首先,这将使在应用程序的多种布局之间切换的过程变得非常困难(例如,如果您想要一种布局用于横向布局,而一种布局用于纵向布局),因为您必须完成Android通常所做的所有工作在onConfigurationChanged()中自动为您创建

无论如何,我也遇到了这类问题。 in onRestoreInstanceState(savedInstanceBundle) ...so this is what I suggest if you cannot use onCreate(savedInstanceBundle) or onActivityCreated(savedInstanceBundle) (for fragments) to restore the state of your view objects: 我正在创建DialogPreference,并且旋转后无法在onRestoreInstanceState(savedInstanceBundle)中更改的进度...因此,这是我建议您不能使用onCreate(savedInstanceBundle)onActivityCreated(savedInstanceBundle) (对于片段)的建议恢复视图对象的状态:

1)创建一个名为“ mRestoredBGColor”的私有类成员,

private int mRestoredBGColor = -1;

2)onRestoreInstanceState()中:

@Override
protected void onRestoreInstanceState(Bundle savedInstanceState) 
       mRestoredBGColor = savedInstanceState.getInt("key_you_used_in_onSaveInstanceState");
}

3)然后在onResume()中 ,因为onRestoreInstanceState()在onStart()之后但在onResume()之前被调用

@Override
public void onResume(){
   super.onResume();
   if(mColorRegion != null && mRestoredBGColor != -1){
       mColorRegion.setBackgroundColor(mRestoredBGColor);
       mRestoredBGColor = -1; //to make sure it only sets this once per rotation.
   }
}

希望这对某人有帮助。 我相信,除了使用android:configChanges="orientation|screenSize"之外,总会有另一种方式(除非您想快速旋转WebViews ...)。

暂无
暂无

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

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