web-dev-qa-db-ja.com

カスタムタイトルバーに背景色のグラデーションをプログラムで設定するにはどうすればよいですか?

そこには多くのチュートリアルと、カスタムタイトルバーを実装するSOに関する質問があります。ただし、カスタムタイトルバーには、背景にカスタムグラデーションがあり、設定方法を知りたいです。私のコードで動的に。

カスタムタイトルバーが呼び出される場所は次のとおりです。

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ファイルにハードコーディングしたくありません。

背景のグラデーションを設定するより良い方法があれば、私はすべてのアイデアを受け入れます。

前もって感謝します!!

63
AngeloS

コードでこれを行うには、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);
166
slund