FloatingActionButton 사용하기



xml)

CoordinatorLayout 으로 감싸주는 것이 좋다

플로팅 액션버튼의 layout_width, layout_height 속성에 크기를 지정할 수 있긴 하지만 너무 크거나 작으면 적용되지 않는다

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
<?xml version="1.0" encoding="utf-8"?>
<android.support.design.widget.CoordinatorLayout xmlns:android="http://schemas.android.com/apk/res/android"
                                                 xmlns:app="http://schemas.android.com/apk/res-auto"
                                                 xmlns:tools="http://schemas.android.com/tools"
                                                 android:layout_width="match_parent"
                                                 android:layout_height="match_parent"
                                                 android:fitsSystemWindows="true">
 
    <RelativeLayout
        android:id="@+id/boxMap"
        android:layout_width="match_parent"
        android:layout_height="match_parent">
        <fragment
            android:id="@+id/map"
            android:layout_weight="1"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:name="com.google.android.gms.maps.SupportMapFragment"/>
 
        <!-- 플로팅 액션 버튼 추가 -->
        <!--
        1. 버튼 색깔 바꿀려면 theme 옵션을 사용하여 colorAccent 색깔을 바꾼다
        2. 크기를 변경할려면 fabSize 옵션을 사용한다 (normal , mini)
        3. 이미지 변경은 src 옵션에서 한다
        -->
        <android.support.design.widget.FloatingActionButton
            android:id="@+id/btnFAB"
            android:layout_alignParentBottom="true"
            android:layout_alignParentRight="true"
            android:layout_margin="16dp"
            app:theme="@style/AppTheme"
            app:fabSize="normal"
            android:elevation="16dp"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:src="@android:drawable/ic_dialog_map" />
    </RelativeLayout>
 
</android.support.design.widget.CoordinatorLayout>
 
cs



java)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
package com.ghj.floatingbtnex;
 
import android.Manifest;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.location.LocationManager;
import android.os.Build;
import android.os.Bundle;
import android.provider.Settings;
import android.support.annotation.NonNull;
import android.support.design.widget.FloatingActionButton;
import android.support.v4.app.ActivityCompat;
import android.support.v4.app.FragmentActivity;
import android.support.v4.content.ContextCompat;
import android.view.View;
import android.widget.RelativeLayout;
import android.widget.Toast;
 
import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.OnMapReadyCallback;
import com.google.android.gms.maps.SupportMapFragment;
import com.google.android.gms.maps.model.LatLng;
 
public class MainActivity extends FragmentActivity implements OnMapReadyCallback {
 
    //GoogleMap 객체
    GoogleMap googleMap;
    LocationManager locationManager;
    RelativeLayout boxMap;
    //나의 위도 경도 고도
    double mLatitude;  //위도
    double mLongitude; //경도
 
 
    FloatingActionButton btnFAB;
 
 
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
 
        boxMap = (RelativeLayout)findViewById(R.id.boxMap);
        btnFAB = (FloatingActionButton)findViewById(R.id.btnFAB);
        btnFAB.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Toast.makeText(MainActivity.this"Click...", Toast.LENGTH_SHORT).show();
            }
        });
 
        //LocationManager
        locationManager = (LocationManager)getSystemService(LOCATION_SERVICE);
        mLatitude = 37.5197889;
        mLongitude = 126.9403083;
 
 
        //GPS가 켜져있는지 체크
        if(!locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER)){
            //GPS 설정화면으로 이동
            Intent intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
            intent.addCategory(Intent.CATEGORY_DEFAULT);
            startActivity(intent);
            finish();
        }
 
        //마시멜로 이상이면 권한 요청하기
        if(Build.VERSION.SDK_INT >= 23){
            //권한이 없는 경우
            if(ContextCompat.checkSelfPermission(MainActivity.this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED ||
                    ContextCompat.checkSelfPermission(MainActivity.this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED){
                ActivityCompat.requestPermissions(MainActivity.thisnew String[]{Manifest.permission.ACCESS_COARSE_LOCATION , Manifest.permission.ACCESS_FINE_LOCATION} , 1);
            }
            //권한이 있는 경우
            else{
                createMap();
            }
        }
        //마시멜로 아래
        else{
            createMap();
        }
    }
 
    //권한 요청후 응답 콜백
    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        //ACCESS_COARSE_LOCATION 권한
        if(requestCode==1){
            //권한받음
            if(grantResults.length>0 && grantResults[0]==PackageManager.PERMISSION_GRANTED){
                createMap();
            }
            //권한못받음
            else{
                Toast.makeText(this"권한없음", Toast.LENGTH_SHORT).show();
                finish();
            }
        }
    }
 
    //맵생성
    public void createMap(){
        //맵생성
        SupportMapFragment mapFragment = (SupportMapFragment)getSupportFragmentManager().findFragmentById(R.id.map);
        //콜백클래스 설정
        mapFragment.getMapAsync(MainActivity.this);
    }
 
    //구글맵 생성 콜백
    @Override
    public void onMapReady(GoogleMap googleMap) {
        this.googleMap = googleMap;
 
        //지도타입 - 일반
        this.googleMap.setMapType(GoogleMap.MAP_TYPE_NORMAL);
 
        //나의 위치 설정
        LatLng position = new LatLng(mLatitude , mLongitude);
 
        //화면중앙의 위치와 카메라 줌비율
        this.googleMap.moveCamera(CameraUpdateFactory.newLatLngZoom(position, 15));
    }
}
 
cs



styles.xml)

1
2
3
4
5
6
7
8
9
10
11
<resources>
 
    <!-- Base application theme. -->
    <style name="AppTheme" parent="Theme.AppCompat.Light.DarkActionBar">
        <!-- Customize your theme here. -->
        <item name="colorPrimary">#489CFF</item>
        <item name="colorPrimaryDark">#489CFF</item>
        <item name="colorAccent">#489CFF</item>
    </style>
 
</resources>
cs



AndroidManifest.xml)

1
2
3
4
5
6
7
...
<!-- Google Map -->
<meta-data android:name="com.google.android.geo.API_KEY" android:value="" />
 
...
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
cs



gladle)

라이브러리 버전에 주의할것

design 라이브러리와 appcompat-v7 라이브러리의 하위버전도 맞춰주는 것이 좋다.

ex) appcompat-v7 의 버전이 24.2.1 이면 24.2 까지는 맞춰줄것

1
2
3
4
5
6
7
dependencies {
    ...
    
    compile 'com.android.support:appcompat-v7:24.2.1'
    compile 'com.android.support:design:24.2.0'
    compile 'com.google.android.gms:play-services-maps:9.8.0'
}
cs



결과

지도위에 플로팅 액션 버튼이 보여진다


+ Recent posts