Computer >> 컴퓨터 >  >> 프로그래밍 >> Android

안드로이드 ActionBar에 커스텀 뷰(Custom View)를 표시하는 방법

이 튜토리얼에서는 안드로이드 ActionBar(액션바)에 커스텀 뷰를 표시하는 방법을 단계별로 살펴봅니다. 기본 제공되는 액션바 대신 자신만의 레이아웃을 적용하고 싶을 때 매우 유용한 기법입니다.

1단계: 새 프로젝트 생성하기

안드로이드 스튜디오(Android Studio)에서 새 프로젝트를 생성합니다. 상단 메뉴에서 File → New Project로 이동한 후, 필요한 정보를 모두 입력하여 새 프로젝트를 만듭니다.

2단계: 메인 레이아웃 작성하기

res/layout/activity_main.xml 파일에 다음 코드를 추가합니다.

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="https://schemas.android.com/apk/res/android" xmlns:app="https://schemas.android.com/apk/res-auto"
    xmlns:tools="https://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity">
    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Custom Action Bar"
        android:textSize="20sp"/>
</LinearLayout>

3단계: 커스텀 액션바 레이아웃 만들기

res/layout/custom_action_bar.xml 파일을 새로 생성하고 다음 코드를 추가합니다.

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
    xmlns:android="https://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:gravity="center_vertical"
    android:padding="10dp"
    android:weightSum="1">
    <LinearLayout
        android:layout_width="0dp"
        android:layout_height="match_parent"
        android:layout_weight="0.6">
        <ImageView
            android:layout_width="wrap_content"
            android:layout_height="match_parent" />
        <TextView
            android:id="@+id/name"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_marginLeft="10dp"
            android:text="Instagram"
            android:textSize="20sp"
            android:textColor="#000"
            android:textStyle="bold" />
    </LinearLayout>
    <LinearLayout
        android:layout_width="0dp"
        android:layout_height="match_parent"
        android:layout_marginRight="10dp"
        android:layout_weight="0.4"
        android:gravity="end">
        <ImageView
            android:layout_width="wrap_content"
            android:layout_height="match_parent" />
        <ImageView
            android:layout_width="wrap_content"
            android:layout_height="match_parent"
            android:layout_marginLeft="20dp" />
    </LinearLayout>
</LinearLayout>

이 레이아웃은 weight(가중치) 속성을 활용해 화면을 6:4 비율로 나눕니다. 왼쪽 영역에는 로고 역할을 하는 ImageView와 'Instagram'이라는 타이틀 텍스트를 배치하고, 오른쪽 영역에는 두 개의 ImageView(예: 검색, 카메라 아이콘 등)를 정렬하여 SNS 앱 스타일의 상단 바를 구성합니다.

4단계: MainActivity 코드 작성하기

src/MainActivity.java 파일에 다음 코드를 추가합니다.

package com.example.sample;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.app.ActionBar;
import android.view.View;
import android.widget.TextView;
import android.widget.Toast;
public class MainActivity extends AppCompatActivity {
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        this.getSupportActionBar().setDisplayOptions(ActionBar.DISPLAY_SHOW_CUSTOM);
        getSupportActionBar().setDisplayShowCustomEnabled(true);
        getSupportActionBar().setCustomView(R.layout.custom_action_bar);
        //getSupportActionBar().setElevation(0);
        View view=getSupportActionBar().getCustomView();
        TextView name=view.findViewById(R.id.name);
        name.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Toast.makeText(MainActivity.this, "You have clicked tittle", Toast.LENGTH_LONG).show();
            }
        });
    }
}

여기서 핵심은 다음 세 줄입니다.

  • setDisplayOptions(ActionBar.DISPLAY_SHOW_CUSTOM): 액션바에 커스텀 뷰를 표시하도록 옵션을 설정합니다.
  • setDisplayShowCustomEnabled(true): 커스텀 뷰 표시 기능을 활성화합니다.
  • setCustomView(R.layout.custom_action_bar): 앞서 만든 커스텀 레이아웃을 액션바에 적용합니다.

또한 getCustomView()로 커스텀 뷰 객체를 가져온 후 findViewById()를 통해 내부의 TextView에 접근하고, 클릭 리스너를 설정해 타이틀 클릭 시 Toast 메시지가 나타나도록 처리했습니다.

5단계: AndroidManifest.xml 확인하기

Manifests/AndroidManifest.xml 파일에 다음 코드를 추가합니다.

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="https://schemas.android.com/apk/res/android" package="com.example.sample">
    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:roundIcon="@mipmap/ic_launcher_round"
        android:supportsRtl="true"
        android:theme="@style/AppTheme">
        <activity android:name=".MainActivity">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>
</manifest>

앱 실행 및 결과 확인

이제 애플리케이션을 실행해 보겠습니다. 실제 안드로이드 모바일 기기가 컴퓨터에 연결되어 있다고 가정합니다. 안드로이드 스튜디오에서 프로젝트의 액티비티 파일 중 하나를 연 상태로 툴바의 Run(실행) 아이콘을 클릭하세요. 목록에서 자신의 모바일 기기를 선택하면, 기기 화면에 커스텀 액션이 적용된 기본 화면이 아래와 같이 표시됩니다.

안드로이드 ActionBar에 커스텀 뷰(Custom View)를 표시하는 방법

이처럼 setDisplayOptions()와 setCustomView()만으로도 기본 액션바를 손쉽게 원하는 디자인으로 교체할 수 있습니다. 여기에 이미지, 버튼, 검색창 등을 추가하면 인스타그램이나 유튜브 같은 앱의 상단 바를 직접 구현할 수 있습니다.