我有一个名为HostFragment
的片段,它嵌套了一到四个其他片段。
这是HostFragment
的布局:
<?xml version="1.0" encoding="utf-8"?>
<TableLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/hostFragmentLayout"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_marginTop="12dp">
<TableRow
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_weight="1">
<RelativeLayout
android:id="@+id/fragmentContainer1"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:layout_weight="1"/>
<RelativeLayout
android:id="@+id/fragmentContainer2"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:layout_weight="1"/>
</TableRow>
<TableRow
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_weight="1">
<RelativeLayout
android:id="@+id/fragmentContainer3"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:layout_weight="1"/>
<RelativeLayout
android:id="@+id/fragmentContainer4"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:layout_weight="1"/>
</TableRow>
</TableLayout>
重要的部分是
android:layout_marginTop="12dp"
。背景:嵌套片段覆盖了整个
HostFragment
,除了这个边距。当嵌套片段改变它们的背景颜色(通过调用 Canvas#drawColor
)时,HostFragment
需要同样改变这个边距的颜色以匹配。我将所需的颜色存储在 SharedPreferences
中。行为:如果用户从
HostFragment
转到 SettingsActivity
,更改颜色,然后返回到 HostFragment
,嵌套片段将立即更改它们的颜色(通过它们的 onResume()
方法),但是 HostFragment
的边距仍然是旧颜色。如果用户然后离开 HostFragment
并转到另一个片段,然后返回到 HostFragment
,边距将更新其颜色。我不知道为什么 - 我没有在 HostFragment
中编写代码来更新颜色。HostFragment
中的代码只涉及交换嵌套片段。
问题: 我需要立即更新边距颜色,所以在onResume()
中,我尝试了一些类似于mTableLayout.setBackgroundColor(...)
甚至是mView.setBackgroundColor(...)
的方法(mView
是我在onCreateView()
中填充的布局),但这仍然无效,只有当用户离开并返回时,颜色才会更新。
问题: 当用户从其他Activity
(例如:从设置页面)返回到HostFragment
后,如何根据SharedPreferences
中的一个int
值来改变边距颜色呢?
提前致谢!
paddingTop
而不是marginTop
,然后在onResume
中通过mView.setBackgroundColor(...)
更改视图的颜色。 - Abhishek V