Android:根据布局文件更改可绘制矩形和ActionBar的颜色

问题描述 投票:0回答:1

我已经停留了一段时间,听起来有些基础。我想使用两个布局文件根据设备的方向更改ActionBar和两个可绘制矩形的颜色。我也有两个活动。

现在,我已将此代码编码到控制器中(在OnResume中调用该函数):

public void changeColor(int orientation) {
    String className = context.getClass().getSimpleName();

    if (orientation == Configuration.ORIENTATION_PORTRAIT) {
        if (className.equals("MainActivity")) {
            // Change actionbar, big square and small square colors
        }
        if (className.equals("WelcomeActivity")) {
            // Change actionbar color
        }
    } else if (orientation == Configuration.ORIENTATION_LANDSCAPE) {
        if (className.equals("MainActivity")) {
            // change actionbar, big square and small square colors
        } else if (className.equals("WelcomeActivity")) {
            // change actionbar color
        }
    }
}

这听起来像可以通过使用人像布局和风景布局来固定它们的颜色不同的东西。这可能吗?现在,使用此功能,听起来像是我在重新发明轮子。

编辑:我的可绘制形状(矩形):

<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android" android:id="@+id/listview_background_shape">
    <padding android:left="2dp"
        android:top="2dp"
        android:right="2dp"
        android:bottom="2dp" />
    <corners android:radius="25dp" />
    <solid android:color="#17D9C5" />
</shape>
java android orientation landscape portrait
1个回答
0
投票

您可以根据设备的方向提供不同的资源。根据您的情况,添加用于肖像的颜色资源文件res/values/colors.xml以及专门用于风景的文件res/values-land/colors.xml

然后,定义颜色在两个文件中像这样

<resources>
    <color name="colorPrimary">#008577</color>
    <color name="colorRectangle1">#00574B</color>
    <color name="colorRectangle2">#D81B60</color>
</resources>

并根据需要使用不同的rgb值。

下一步,使用Activity主题中的颜色资源。您可以在Activity中设置Manifest.xml的主题,然后在res/values/styles.xml中声明。 ActionBar的颜色由

确定
<item name="colorPrimary">@color/colorPrimary</item>

最后,同样重要的是,使用可绘制资源文件中的颜色资源:

<shape xmlns:android="http://schemas.android.com/apk/res/android" android:id="@+id/listview_background_shape">
    <padding android:left="2dp"
        android:top="2dp"
        android:right="2dp"
        android:bottom="2dp" />
    <corners android:radius="25dp" />
    <solid android:color="@color/colorRectangle1" />
</shape>
© www.soinside.com 2019 - 2024. All rights reserved.