Programming/국비학원

220531 - 안드로이드 구현 실습 (AlertDialog)

지고르 2022. 6. 1. 10:35
seoultour (계속)
  • 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="위성 지도"/>
        <RadioButton
            android:id="@+id/rdoTerrain"
            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.example.seoultour1;

import androidx.annotation.NonNull;
import androidx.fragment.app.FragmentActivity;

import android.content.Intent;
import android.net.Uri;
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.BitmapDescriptorFactory;
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.example.seoultour1.databinding.ActivityMapsBinding;

public class MainActivity extends FragmentActivity implements OnMapReadyCallback {

    private GoogleMap mMap;
    private ActivityMapsBinding binding;
    RadioGroup rGroup;
    RadioButton rdoNormal, rdoHybrid, rdoTerrain;
    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};
    String addr[]={"이젠아카데미학원","서울특별시 용산구 서빙고로 137",
            "서울특별시 중구 퇴계로34길 28","서울특별시 서초구 남부순환로 2364",
            "서울특별시 종로구 창신동","서울특별시 영등포구 63로 50",
            "서울특별시 용산구 남산공원길 105","서울특별시 종로구 삼청로 37",
            "서울특별시 중구 명동2가 32-2","서울특별시 송파구 올림픽로 448",
            "서울특별시 종로구 삼청로 37","서울특별시 서대문구 통일로 251",
            "서울특별시 종로구 율곡로 99"};
    String tel[]={"02-777-7777","02-2264-4412","02-580-1300",
            "02-2290-6114","02-789-5663","02-3455-9277",
            "02-3700-3900","02-318-7051","02-410-1354",
            "02-3704-3114","02-360-8590","02-762-8261","02-762-8261"};
    String homepage[]={"http://myhome","http://www.museum.go.kr",
            "http://hanokmaeul.seoul.go.kr","http://www.sac.or.kr",
            "http://www.cheonggyecheon.or.kr",
            "http://www.63.co.kr","http://www.nseoultower.com",
            "http://www.royalpalace.go.kr",
            "http://www.visitseoul.net/kr/article/article.do?_method=view&art_id=49160&lang=kr&m=0004003002009&p=03",
            "http://www.88olympic.or.kr","http://www.nfm.go.kr",
            "http://www.sscmc.or.kr/culture2","http://www.cdg.go.kr"};
    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);
        rdoTerrain = findViewById(R.id.rdoTerrain);
        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) {

            }
        });

        //라디오그룹의 라디오버튼을 체인지했을 때 처리하는 메서드
        rGroup.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(RadioGroup group, int checkedId) {
                switch(checkedId){
                    case R.id.rdoNormal:
                        mMap.setMapType(GoogleMap.MAP_TYPE_NORMAL);
                        break;
                    case R.id.rdoHybrid:
                        mMap.setMapType(GoogleMap.MAP_TYPE_HYBRID);
                        break;
                    case R.id.rdoTerrain:
                        mMap.setMapType(GoogleMap.MAP_TYPE_TERRAIN);
                        break;
                }
            }
        });
    }

    @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]));
        MarkerOptions marker = new MarkerOptions();  //마커 세팅
        marker.position(tourLatlog);
        marker.title(addr[pos]);
        marker.snippet(tel[pos]);  //부가설명란
        marker.icon(BitmapDescriptorFactory.fromResource(R.drawable.pin));
        mMap.addMarker(marker).showInfoWindow();


        //타이틀/부가설명 클릭 -> 전화
        mMap.setOnInfoWindowClickListener(new GoogleMap.OnInfoWindowClickListener() {
            @Override
            public void onInfoWindowClick(@NonNull Marker marker) {
                Intent mintent = new Intent(Intent.ACTION_DIAL, Uri.parse("tel:/"+tel[pos]));
                startActivity(mintent);
            }
        });


        //마커 클릭 -> 홈페이지
        mMap.setOnMarkerClickListener(new GoogleMap.OnMarkerClickListener() {
            @Override
            public boolean onMarkerClick(@NonNull Marker marker) {
                Intent mintent = new Intent(Intent.ACTION_VIEW, Uri.parse("http://"+homepage[pos]));
                startActivity(mintent);
                return false;
            }
        });

    }//mapShow

}

 

 

 

NumberGame
  • 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"
    android:padding="20dp"
    tools:context=".MainActivity">

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="1부터 100 사이의 숫자 맞추기 게임"
        android:textSize="20dp"
        android:layout_marginBottom="20dp"
        android:layout_gravity="center"
        android:textColor="#6799FF" />

    <EditText
        android:id="@+id/edtNumber"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:hint="숫자입력"
        android:textAlignment="center"
        android:inputType="number"
        android:layout_marginBottom="20dp"
        android:layout_gravity="center"/>

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:gravity="center">

        <Button
            android:id="@+id/btnGameStart"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_marginRight="80dp"
            android:backgroundTint="#6799FF"
            android:text="게임시작"/>

        <Button
            android:id="@+id/btnConfirm"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:backgroundTint="#6799FF"
            android:enabled="false"
            android:text="확인"/>

    </LinearLayout>

    <TextView
        android:id="@+id/tvHint"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginTop="20dp"
        android:textSize="20dp"
        android:textColor="#ff0000"/>

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:gravity="center"
        android:layout_weight="1"
        android:orientation="vertical">

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

    </LinearLayout>

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_gravity="center"
        android:orientation="horizontal">

        <Button
            android:id="@+id/btnMenuAuto"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:visibility="invisible"
            android:layout_marginRight="100dp"
            android:text="내기 메뉴 자동 선택"/>

        <Button
            android:id="@+id/btnFinish"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="앱 종료"/>

    </LinearLayout>

</LinearLayout>

 

 

  • java

package com.example.numbergame;

import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;

import android.content.DialogInterface;
import android.os.Bundle;
        import android.view.View;
        import android.view.inputmethod.InputMethodManager;
        import android.widget.Button;
        import android.widget.EditText;
        import android.widget.ImageView;
        import android.widget.TextView;
        import android.widget.Toast;


public class MainActivity extends AppCompatActivity {
    //객체, 변수 선언
    EditText edtNumber;
    Button btnGameStart, btnConfirm, btnMenuAuto, btnFinish;
    TextView tvHint;
    ImageView imgGame;
    int comNum;
    int count;
    int myNum;
    String[] menu = {"커피", "떡볶이","순대","어묵","짜장면"};
    int choice;  //선택 번호 (랜덤)

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        setTitle("숫자 맞추기 게임");

        //선언된 객체를 xml 위젯과 연결 (casting)
        edtNumber = findViewById(R.id.edtNumber);
        btnGameStart = findViewById(R.id.btnGameStart);
        btnConfirm = findViewById(R.id.btnConfirm);
        btnMenuAuto = findViewById(R.id.btnMenuAuto);
        btnFinish = findViewById(R.id.btnFinish);
        tvHint = findViewById(R.id.tvHint);
        imgGame = findViewById(R.id.imgGame);
        tvHint.setText("게임 시작 버튼을 누르면 게임이 시작됩니다");
        InputMethodManager inputmm = (InputMethodManager) getSystemService(INPUT_METHOD_SERVICE);  //input(키보드) 관련 서비스 소환


        //메서드로 기능 처리
        //게임시작 버튼 메서드
        btnGameStart.setOnClickListener(new View.OnClickListener() {  //온클릭리스너 인터페이스
            @Override
            public void onClick(View v) {  //추상메서드 오버라이드
                comNum = (int)(Math.random()*100)+1;
                count=0;
                tvHint.setText("자 게임이 시작되었습니다!");
                btnConfirm.setEnabled(true);
                btnGameStart.setEnabled(false);
                btnMenuAuto.setVisibility(View.INVISIBLE); //메뉴 선택 버튼 다시 숨기기
            }
        });

        //확인 버튼 메서드
        btnConfirm.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                try{
                    count++;
                    myNum = Integer.parseInt(edtNumber.getText().toString());
                    if (myNum>comNum){
                        tvHint.setText("숫자가 커요.\n더 작은 숫자를 넣어봐요 ("+count+")");
                    }else if (myNum<comNum){
                        tvHint.setText("숫자가 작아요.\n더 큰 숫자를 넣어봐요 ("+count+")");
                    }else {
                        tvHint.setText("정답! 축하합니다 ("+count+")");
                        btnConfirm.setEnabled(false);
                        btnGameStart.setEnabled(true);
                        inputmm.hideSoftInputFromWindow(edtNumber.getWindowToken(),0);  //키보드 숨기기
                        btnMenuAuto.setVisibility(View.VISIBLE);  //메뉴 선택 버튼 보이기
                    }
                    edtNumber.setText("");
                } catch(NumberFormatException e){
                    Toast.makeText(getApplicationContext(),"숫자를 입력해주세요",Toast.LENGTH_SHORT).show(); //g: 내 앱 화면에
                }
            }//onclick
        });

        //복불복 메뉴 선택 메서드
        btnMenuAuto.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                choice=(int)(Math.random()*menu.length);
                tvHint.setText("당첨!! 복불복 내기 메뉴는 바로 "+menu[choice]+"입니다!");
            }
        });

        //앱 종료 버튼 메서드
        btnFinish.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);
                builder.setMessage("정말 종료하시겠습니까?");
                builder.setNegativeButton("예", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        finish();
                    }
                });
                builder.setPositiveButton("아니오",null);
                builder.show();
            }
        });

    }//OnCreate

}

 

 

 

ListApp
  • 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/btnSave"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="자료 등록"/>

    <ListView
        android:id="@+id/list1"
        android:layout_width="match_parent"
        android:layout_height="0dp"
        android:layout_weight="2"/>

    <TextView
        android:id="@+id/tvContent"
        android:layout_width="match_parent"
        android:layout_height="0dp"
        android:layout_weight="1"
        android:textSize="20dp"/>

</LinearLayout>

 

 

  • xml:  dialog

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

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content">
        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="제목"/>
        <EditText
            android:id="@+id/dialogTitle"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            />
    </LinearLayout>
    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content">
        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="내용"/>
        <EditText
            android:id="@+id/dialogContent"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            />
    </LinearLayout>

</LinearLayout>

 

 

  • java

package com.example.listapp;

import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;

import android.content.DialogInterface;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import java.util.ArrayList;

public class MainActivity extends AppCompatActivity {
    ListView list1;
    TextView tvContent;
    Button btnSave;
    ArrayAdapter<String> adapter;
    ArrayList<String> title;
    ArrayList<String> content;
    EditText dialogTitle, dialogContent; //연결보류 => Alertdialog 생성 후 dialogView.findView~로 연결함
    View dialogView;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        list1 = findViewById(R.id.list1);
        tvContent = findViewById(R.id.tvContent);
        btnSave = findViewById(R.id.btnSave);
        title = new ArrayList<String>();
        content = new ArrayList<String>();

        adapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1,title);
        list1.setAdapter(adapter);  //spinner-list 위치만 바뀐 격

        //리스트뷰 아이템 클릭->텍스트뷰에 내용 출력
        list1.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                tvContent.setText(content.get(position));
            }
        });

        //리스트뷰 아이템 롱클릭->삭제 다이얼로그
        list1.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
            @Override
            public boolean onItemLongClick(AdapterView<?> parent, View view, int position, long id) {
                AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);
                builder.setMessage("삭제하시겠습니까?");
                builder.setIcon(R.drawable.bob);
                builder.setTitle("스케줄 삭제");
                builder.setNegativeButton("예", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        title.remove(position);
                        content.remove(position);
                        adapter.notifyDataSetChanged();  //어댑터 리셋
                    }
                });
                builder.setPositiveButton("아니오", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        Toast.makeText(getApplicationContext(),"삭제 취소",Toast.LENGTH_SHORT).show();
                    }
                });
                builder.show();
                return false;
            }
        });

        //자료 등록 버튼
        btnSave.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                dialogView = View.inflate(MainActivity.this,R.layout.dialog,null);
                //dialog.xml을 inflate해서 Main에 띄움
                AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);
                builder.setTitle("스케줄 등록");
                builder.setIcon(R.drawable.bob);
                builder.setView(dialogView);
                dialogTitle = dialogView.findViewById(R.id.dialogTitle);
                dialogContent = dialogView.findViewById(R.id.dialogContent);
                builder.setNegativeButton("등록", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        title.add(dialogTitle.getText().toString());
                        content.add(dialogContent.getText().toString());
                    }
                });
                builder.setPositiveButton("취소",null);
                builder.show();
            }
        });

    }
}