Android - 实现背景调光效果

Android - achieve dimming of background effect

我正在构建一个背景变暗的启动画面。我使用 RelativeLayout 作为所有小部件的基础。为了创建和调暗效果,我创建了一个 dim.xml,它本质上是一个黑色形状(稍后设置不透明度)。

<?xml version="1.0" encoding="utf-8"?>
<shape
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:shape="rectangle" >
    <solid android:color="#000000" />

布局:

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:background="@drawable/background"
    android:id="@+id/ActivityLayout">

    <ImageView
        android:layout_width="240dp"
        android:layout_height="@dimen/abc_action_bar_default_height_material"
        android:layout_marginTop="98dp"
        android:layout_marginRight="170dp"
        android:src="@drawable/logo"
        android:id="@+id/logo" />

</RelativeLayout>

有没有办法在RelativeLayout和小部件之间放置黑色形状,然后为黑色形状设置一些alpha值以达到调光效果?

Is there a way to place the black shape between the RelativeLayout and the widgets, and then set some alpha value to the black shape in order to achieve the dimming effect?

您可以通过在 RelativeLayout 中添加另一个 View 并将其宽度和高度设置为 "match_parent",然后将视图的背景颜色更改为您想要的颜色来实现。

您的布局可能是这样的:

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" 
  ...  
>

<View android:width="match_parent"
      android:height="match_parent"
      android:background="@color/the_color_you_want"/>

<here are the widgets...>

</RelativeLayout>

更新:

But it doesnt fill the entire view port, the there's about 10dp margin on each side, that doesnt stretches across the screen. Any way to fill the entire screen?

这是因为您为 RelativeLayout 的左侧和右侧设置了 10dp 的内边距。有两种方法可以让彩色View填满整个屏幕:

  1. android:clipToPadding="false" 设置为您的 RelativeLayout,然后将以下属性设置为颜色视图:

android:layout_marginLeft="-10dp"
android:layout_marginRight="-10dp"

这很容易做到,但它可能会导致您的小部件出现问题,因此您可以尝试一下。

  1. 从您的 RelativeLayout 中删除 paddingLeftpaddingRight 属性,因此您的颜色 View 将填满屏幕,然后重新排列您的小部件以确保它们的左侧或右侧保证金是正确的。

您可能需要使用此方法做更多的工作,但我确信这是正确的方法。