본문 바로가기

Programming/국비학원

220530 - 안드로이드 구현 실습 (Scroll, Spinner, 구글맵 불러오기)

스크롤
  • 수직 스크롤

<?xml version="1.0" encoding="utf-8"?>
<ScrollView 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:orientation="vertical"
    tools:context=".MainActivity">

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:orientation="vertical">
    <Button
        android:layout_width="match_parent"
        android:layout_height="100dp"
        android:text="나는 버튼1" />
    <Button
        android:layout_width="match_parent"
        android:layout_height="100dp"
        android:text="나는 버튼2" />
    <Button
        android:layout_width="match_parent"
        android:layout_height="100dp"
        android:text="나는 버튼3" />
    </LinearLayout>

</ScrollView>

 

 

  • 수평 스크롤

<?xml version="1.0" encoding="utf-8"?>
<HorizontalScrollView 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:orientation="vertical"
    tools:context=".MainActivity">

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:orientation="horizontal">
    <Button
        android:layout_width="match_parent"
        android:layout_height="100dp"
        android:text="나는 버튼1" />
    <Button
        android:layout_width="match_parent"
        android:layout_height="100dp"
        android:text="나는 버튼2" />
    <Button
        android:layout_width="match_parent"
        android:layout_height="100dp"
        android:text="나는 버튼3" />
    </LinearLayout>

</HorizontalScrollView>

 

 

  • 사진 순차 바꾸기
  • xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout 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:orientation="vertical"
    tools:context=".MainActivity">

    <Button
        android:id="@+id/btnChange"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="이미지 바꿔 보여주기"/>

    <HorizontalScrollView
        android:layout_width="match_parent"
        android:layout_height="match_parent">
        <ScrollView
            android:layout_width="wrap_content"
            android:layout_height="match_parent">
            <ImageView
                android:id="@+id/img1"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:src="@drawable/image01"/>
        </ScrollView>
    </HorizontalScrollView>
</LinearLayout>

 

 

  • java

package com.hk.scrollapp;

import androidx.appcompat.app.AppCompatActivity;

import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;

public class MainActivity extends AppCompatActivity {
    ImageView img1;
    Button btnChange;
    Integer[] imgs = {R.drawable.image01, R.drawable.image02,
            R.drawable.lighthouse, R.drawable.penguins, R.drawable.tulips };
    int count=0;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        btnChange = findViewById(R.id.btnChange);
        img1 = findViewById(R.id.img1);

        btnChange.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (count==4){
                    count=0;
                };
                img1.setImageResource(imgs[count+1]);
                count++;
            }
        });
    }
}

 

 

Spinner

= 어댑터 뷰 (콤보바와 유사)

 

=> 어댑터 (콤보목록박스) 장착 필요

 

 

  • xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout 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:orientation="vertical"
    tools:context=".MainActivity">

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="영화 흥행 순위"
        android:layout_gravity="center"
        android:textSize="20dp"/>

    <Spinner
        android:id="@+id/spinner1"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"/>

    <TextView
        android:id="@+id/txtStory"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginTop="10dp"
        android:textSize="20dp"
        android:layout_gravity="center"/>

    <ImageView
        android:id="@+id/imgs"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center"/>

</LinearLayout>

 

 

  • java

package com.hk.spinnerapp;

import androidx.appcompat.app.AppCompatActivity;

import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;

public class MainActivity extends AppCompatActivity {
    Spinner spinner1;
    String movies[]= {"써니","완득이","괴물","라디오스타", "비열한 거리",
            "왕의 남자","아일랜드","웰컴투동막골","헬보이","백투더퓨처"};
    String[] story = {"7공주 이야기","나만 가지고 왜 이래","한강에 나타난 괴물과 가족의 사투",
            "진정한 스타","조폭","사극","복제","남북한","싸움","과거"};
    TextView txtStory;
    ImageView imgs;
    Integer[] imgG = {R.drawable.mov01,R.drawable.mov02,R.drawable.mov03,R.drawable.mov04,R.drawable.mov05,R.drawable.mov06,
            R.drawable.mov07,R.drawable.mov08,R.drawable.mov09,R.drawable.mov10};
    ArrayAdapter<String> adapter;
    
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);  //xml 보여줌
        spinner1=findViewById(R.id.spinner1);
        imgs = findViewById(R.id.imgs);
        txtStory = findViewById(R.id.txtStory);

        adapter = new ArrayAdapter<String>(this,android.R.layout.simple_spinner_dropdown_item, movies);
        //this : 현재 액티비티의 스피너에 어댑터 장착, simple_spinner_item : 어댑터 모양
        spinner1.setAdapter(adapter);

        //스피너 자료선택
        spinner1.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                ///position : 어댑터 위치값 (movies[])
                txtStory.setText(story[position]);
                imgs.setImageResource(imgG[position]);
                Toast.makeText(getApplicationContext(),movies[position]+"을(를) 선택했습니다.",Toast.LENGTH_SHORT).show();
            }

            @Override
            public void onNothingSelected(AdapterView<?> parent) {
            }
        });
    }
}

 

 

 

서울 관광지 지도 - 스피너, 구글맵연결 

=> new empty google map project
console.developers.google.com/apis/
API 안드로이드 => 사용자 인증 정보

 

 

  • xml

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    package="com.hk.seoultour1">

    <application
        android:allowBackup="true"
        android:dataExtractionRules="@xml/data_extraction_rules"
        android:fullBackupContent="@xml/backup_rules"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:roundIcon="@mipmap/ic_launcher_round"
        android:supportsRtl="true"
        android:theme="@style/Theme.SeoulTour1"
        tools:targetApi="31">

        <!--
             TODO: Before you run your application, you need a Google Maps API key.

             To get one, follow the directions here:

                https://developers.google.com/maps/documentation/android-sdk/get-api-key

             Once you have your API key (it starts with "AIza"), define a new property in your
             project's local.properties file (e.g. MAPS_API_KEY=Aiza...), and replace the
             "YOUR_API_KEY" string in this file with "${MAPS_API_KEY}".
        -->
        <meta-data
            android:name="com.google.android.geo.API_KEY"
            android:value="사용자 키" />

        <activity
            android:name=".MapsActivity"
            android:exported="true"
            android:label="@string/title_activity_maps">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>

</manifest>

 

 

  • activity_maps.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:map="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MapsActivity"
    android:orientation="vertical">

    <RadioGroup
        android:id="@+id/rGroup"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="horizontal">
        <RadioButton
            android:id="@+id/rdoNormal"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:checked="true"
            android:text="일반 지도"/>
        <RadioButton
            android:id="@+id/rdoHybrid"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:text="위성 지도"/>
    </RadioGroup>

    <Spinner
        android:id="@+id/spTour"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"/>

    <fragment
        android:id="@+id/map"
        android:name="com.google.android.gms.maps.SupportMapFragment"
        android:layout_width="match_parent"
        android:layout_height="match_parent"/>

</LinearLayout>

 

 

  • java

package com.hk.seoultour1;

import androidx.fragment.app.FragmentActivity;

import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.Spinner;

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;
import com.google.android.gms.maps.model.Marker;
import com.google.android.gms.maps.model.MarkerOptions;
import com.hk.seoultour1.databinding.ActivityMapsBinding;

public class MapsActivity extends FragmentActivity implements OnMapReadyCallback {

    private GoogleMap mMap;
    private ActivityMapsBinding binding;
    RadioGroup rGroup;
    RadioButton rdoNormal, rdoHybrid;
    Spinner spTour;
    int pos;
    String seoul[] ={"이젠아카데미","국립중앙박물관","남산골 한옥마을",
            "예술의 전당","청계천","63빌딩","서울타워","경복궁","김치문화체험관",
            "서울올림픽기념관","국민민속박물관","서대문형무소역사관","창덕궁"};
    // 위도(Latitude) 설정
    Double lat[]={37.569845,37.5240867,37.5591447,37.4785361,37.5696512,
            37.5198158,37.5511147,37.5788408,37.5629457,37.5202976,
            37.5815645,37.5742887,37.5826041};
    //경도(Longitude) 설정
    Double log[]={126.984859,126.9803881,126.9936826,127.0107423,
            127.0056375,126.9403139,126.9878596,126.9770162,126.9851652,
            127.1159236,126.9789313,126.9562269,126.9919376};
    ArrayAdapter<String> adapter;
    Double[] tourLocation = new Double[2];  //현재 관광지 위도, 경도 배열

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        binding = ActivityMapsBinding.inflate(getLayoutInflater());
        setContentView(binding.getRoot());
        rGroup = findViewById(R.id.rGroup);
        rdoHybrid = findViewById(R.id.rdoHybrid);
        rdoNormal = findViewById(R.id.rdoNormal);
        spTour = findViewById(R.id.spTour);
        SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager()
                .findFragmentById(R.id.map);
        mapFragment.getMapAsync(this);

        adapter = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_dropdown_item,seoul);
        spTour.setAdapter(adapter);
        spTour.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                tourLocation[0]=lat[position];
                tourLocation[1]=log[position];
                pos=position;
                mapShow(tourLocation);
            }

            @Override
            public void onNothingSelected(AdapterView<?> parent) {

            }
        });
    }

    @Override
    public void onMapReady(GoogleMap googleMap) {
        mMap = googleMap;

    //서울 관광 지도
    public void mapShow(Double[] latlog){
        LatLng tourLatlog = new LatLng(latlog[0],latlog[1]);
        mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(tourLatlog,15));
        mMap.addMarker(new MarkerOptions().position(tourLatlog).title(seoul[pos]));
    }
}

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

//

실습하면서 느낀 점 : findview로 연결을 안 하는 등 사소한 실수를 해서 구현에 실패하는 경우가 있다. 로직을 짜는 것도 중요하지만 이런 실수들로 코드 완성 못하는 일은 만들지 말자.