Android - 更改保证金的背景颜色

pez*_*pez 5 android android-layout xml-layout

我有一个命名的片段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>
Run Code Online (Sandbox Code Playgroud)

其中重要的部分是android:layout_marginTop="12dp".

背景:嵌套片段覆盖HostFragment除此边距之外的整体.当嵌套片段改变其背景颜色(通过调用Canvas#drawColor)时,HostFragment还需要更改此边距的颜色以匹配.我存储了所需的颜色SharedPreferences.

行为:如果用户从去HostFragmentSettingsActivity,改变颜色,并且回来HostFragment,嵌套的片段将立即(通过他们改变自己的颜色onResume()的方法),但HostFragment"保证金将仍然是旧的颜色.如果用户然后离开HostFragment并转到另一个片段,然后返回HostFragment,则边距将更新其颜色.我不知道如何或为什么 - 我没有代码HostFragment来更新颜色.该代码HostFragment仅涉及交换嵌套片段.

问题:我需要立即更新边距颜色,因此onResume(),我尝试了类似mTableLayout.setBackgroundColor(...)甚至是mView.setBackgroundColor(...)(mView我正在膨胀的布局onCreateView()).这仍然不起作用,只有当用户离开并返回时颜色才会更新.

问题:如果用户从另一个用户返回(用户从"设置"返回后),可以如何更改边距的颜色以匹配int值?SharedPreferencesHostFragmentActivity

先感谢您!

Abh*_*k V 5

先给paddingTop代替marginTop,然后更改视图的颜色onResume通过mView.setBackgroundColor(...).

  • 边距是视图外的空间,因此视图的背景颜色不会反映在边距空间中.
  • 填充是视图内部的空间,给予视图的背景颜色也将应用于填充空间.