【发布时间】:2016-05-21 06:20:57
【问题描述】:
我正在尝试通过设置页面更改整个应用程序的背景颜色,我已经搜索了很长时间,至今找不到解决方案。
所以,在片段内部我有一个按钮,它充当一个切换开关。单击时,背景颜色会发生应有的变化,从白色到灰色交替变化。
这里是按钮的逻辑:
Button changeBGButton = (Button) view.findViewById(R.id.btn_change_bg);
changeBGButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if (((MainActivity)getActivity()).bgWhite == true)
{
//White is true, set to grey
((MainActivity)getActivity()).bgWhite = false;
((MainActivity)getActivity()).bgGrey = true;
Toast.makeText(getActivity(), "Set is white to false, grey to true.", Toast.LENGTH_SHORT).show();
}
else if (((MainActivity)getActivity()).bgWhite == false && ((MainActivity)getActivity()).bgGrey == true)
{
//White is true, set to grey
((MainActivity)getActivity()).bgWhite = true;
((MainActivity)getActivity()).bgGrey = false;
Toast.makeText(getActivity(), "Set is white to true, grey to false.", Toast.LENGTH_SHORT).show();
}
}
});
OnCreateView 覆盖方法内部的主要活动负责更改背景颜色,并且确实如此。单击按钮后,它会发生变化。
但是…… 当按下后退按钮返回到后台堆栈中的上一个屏幕时,背景变为白色,如果我再次进入设置页面,它是灰色的,并且在按下返回时再次变为白色。
就好像只有fragment改变了背景,但是布局contentLayout只存在于mainLayout而不是fragment上。
我怀疑在调用 Fragment Lifecycle Methods 期间背景正在被重置,但我不知道如何让它持续存在,因为按下后退按钮时没有保存实例。
无论如何。下面是改变背景的逻辑,包括覆盖方法:
@Override
public View onCreateView(View parent, String name, Context context, AttributeSet attrs)
{
if (contentMain != null) //Only do this if we have a hope at not crashing the application/
if (bgWhite == true && bgGrey == false)
{
contentMain.setBackgroundColor(Color.parseColor("#FFFFFF"));
}
else if (bgGrey == true && bgWhite == false)
{
contentMain.setBackgroundColor(Color.parseColor("#888888"));
}
return super.onCreateView(parent, name, context, attrs);
}
我也尝试在 OnBackstackChangeListener 内部执行此操作,但结果相同。请帮帮我。
干杯。
【问题讨论】:
标签: android android-layout android-fragments android-studio