Programing

사용자 지정 제목 표시 줄에서 프로그래밍 방식으로 배경색 그라데이션을 설정하려면 어떻게합니까?

lottogame 2020. 11. 23. 07:36
반응형

사용자 지정 제목 표시 줄에서 프로그래밍 방식으로 배경색 그라데이션을 설정하려면 어떻게합니까?


사용자 지정 제목 표시 줄을 구현하는 많은 자습서와 질문이 있습니다. 그러나 내 사용자 지정 제목 표시 줄에는 배경에 대한 사용자 지정 그라데이션이 있으며 코드에서 동적으로 설정하는 방법을 알고 싶습니다.

내 사용자 지정 제목 표시 줄이 호출되는 위치는 다음과 같습니다.

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);

참고 URL : https://stackoverflow.com/questions/6115715/how-do-i-programmatically-set-the-background-color-gradient-on-a-custom-title-ba

반응형