[Android] App Bar Custom

by 민갤

Android /

안드로이드 앱의 상단에 있는 바를 App Bar라고 한다. (ActionBar, Toolbar 등)

이 앱 바를 직접 만들어 보자.

1. 디자인 하기

layout을 하나 생성하여 상단에 보여주고 싶은 앱 바를 만든다. 

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout ...
              android:layout_width="match_parent"
              android:layout_height="match_parent">

    <ImageButton
        android:id="@+id/btn_list"
        ... />

    <TextView
        android:id="@+id/title"
        ... />

    <ImageButton
        android:id="@+id/btn_option"
        ... />

</RelativeLayout>

2. 색상 지정하기

앱 바의 색상은 styles.xml 에서 지정한다.

필자는 안드로이드 스튜디오가 친절하게 마련해준 style을 이용해서 만든다.

<resources>

    <!-- Base application theme. -->
    <style name="AppTheme" parent="Theme.AppCompat.Light.DarkActionBar">
        <!-- Customize your theme here. -->
        <item name="colorPrimary">@color/colorPrimary</item>
        <item name="colorPrimaryDark">@color/colorPrimaryDark</item>
        <item name="colorAccent">@color/colorAccent</item>
        <item name="actionBarSize">45dp</item>
    </style>

</resources>
  • colorPrimary :  앱 바의 색상을 지정한다.
  • colorPrimaryDark : 앱 바 위의 상태 표시줄의 색상을 지정한다.
  • colorAccent : ProgressBar, CheckBox, 밑줄 표시 등 강조 표시의 색상을 지정한다.
  • actionBarSize :  앱 바의 높이를 지정한다.

3. 테마 지정하기

AndroidManifest의 application theme를 본인이 만든 style로 지정해준다.

  • 기본
<application
        ...
        android:theme="@style/AppTheme">
  • 지정
<application
        ...
        android:theme="@style/yourCustomThemeStyleName">

4. 사용자가 정의한 앱 바 사용하기

직접 만든 앱 바를 보여주고 싶은 Activity에 다음 코드를 입력한다.

import android.support.v7.app.ActionBar;

...

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
       
	...

        ActionBar actionBar = getSupportActionBar();
        actionBar.setDisplayOptions(ActionBar.DISPLAY_SHOW_CUSTOM);
        actionBar.setCustomView(R.layout.custom_bar);
        actionBar.setElevation(0);
    }
}
  • ActionBar의 import : 지원 라이브러리 support.v7.app
  • setDisplayOptions :  DISPLAY_SHOW_CUSTOM을 입력해 사용자가 정의한 뷰를 사용하도록 지정한다.
  • setCustomView :  사용자가 지정한 뷰(layout)를 보여준다.
  • setElevation :  앱 바의 Z축 높이를 조정한다. 0을 입력하면 그림자가 보이지 않는다.

만일 특정 Activity에서는 앱 바를 보이고 싶지 않다면 다음 코드를 입력한다.

actionBar.hide();

5. Java 코드 내에서 앱 바 수정하기

코드 내에서 Title 내용을 바꾸고 싶다면 View를 inflate 한 후 그것을 setCustomView 한다.

LayoutInflater inflater = LayoutInflater.from(this);
View v = inflater.inflate(R.layout.custom_bar, null);
TextView tv_title = (TextView)v.findViewById(R.id.title);
tv_title.setText("hello");
actionBar.setCustomView(v);

Author

민갤

민갤

Back-End Developer

꾸잉꾸잉하고 웁니다.

로그인

디코에 오신 것을 환영해요!
전문가들의 수많은 아티클 창고 🤓