如何以编程方式设置自定义标题栏上的背景颜色渐变?

2023-11-21

有很多关于实现自定义标题栏的教程和问题。但是,在我的自定义标题栏中,我有一个自定义背景渐变,我想知道如何在我的代码中动态设置它。

这是我的自定义标题栏被调用的地方:

requestWindowFeature(Window.FEATURE_CUSTOM_TITLE);
setContentView(R.layout.foo_layout);
getWindow().setFeatureInt(Window.FEATURE_CUSTOM_TITLE, R.layout.custom_title_bar); 

这是我的custom_title_bar:

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="horizontal"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:background="@layout/custom_title_bar_background_colors">
<ImageView   
              android:layout_width="fill_parent"
              android:layout_height="wrap_content"
              android:src="@drawable/title_bar_logo"
              android:gravity="center_horizontal"
              android:paddingTop="0dip"/>

</LinearLayout>

正如你所看到的,线性布局的背景是由这个人定义的:

<shape xmlns:android="http://schemas.android.com/apk/res/android">
<gradient 
    android:startColor="#616261" 
    android:endColor="#131313"
    android:angle="270"
 />
<corners android:radius="0dp" />
</shape>

我想做的是在我的代码中动态设置这些渐变颜色。我不想像现在一样将它们硬编码到我的 XML 文件中。

如果您有更好的设置背景渐变的方法,我愿意接受所有想法。

先感谢您!!


要在代码中执行此操作,您需要创建一个 GradientDrawable。
设置角度和颜色的唯一机会是在构造函数中。 如果你想改变颜色或角度,只需创建一个新的 GradientDrawable 并将其设置为背景

    View layout = findViewById(R.id.mainlayout);

    GradientDrawable gd = new GradientDrawable(
            GradientDrawable.Orientation.TOP_BOTTOM,
            new int[] {0xFF616261,0xFF131313});
    gd.setCornerRadius(0f);

    layout.setBackgroundDrawable(gd);

为此,我向您的主 LinearLayout 添加了一个 id,如下所示

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/mainlayout"
    android:orientation="horizontal"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent">
<ImageView   
              android:layout_width="fill_parent"
              android:layout_height="wrap_content"
              android:src="@drawable/title_bar_logo"
              android:gravity="center_horizontal"
              android:paddingTop="0dip"/>

</LinearLayout>

并将其用作自定义标题栏

    getWindow().setFeatureInt(Window.FEATURE_CUSTOM_TITLE,R.layout.custom_title_bar);
    View title = getWindow().findViewById(R.id.mainlayout);
    title.setBackgroundDrawable(gd);
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

如何以编程方式设置自定义标题栏上的背景颜色渐变? 的相关文章

随机推荐