안드로이드 버튼 생성 방법 중 layoutButton을 정의 하고 Acitvity 생성 단계인 onCreate() 함수에서 버튼의 생성과 동시에 OnClickListener를 구현 하는 방법 입니다.

public void setOnClickListener (View.OnClickListener l)를 이용하여 등록 합니다.

 

1. Layout에 이벤트 추가


activity_main.xmlButtonLayout을 구성 합니다.


<Button
android:id="@+id/btn_listener1"
android:text="@string/btn_listen1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="10dp"
android:layout_marginTop="100dp"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintTop_toTopOf="parent" />

ID를 달리 해서 3개의 버튼을 추가 했습니다.

 

2. Activity에 기능 구현

 

onCreate()에서 다음과 같은 형태고 버튼 3개를 정의 합니다.


Button btnListener1 = (Button)findViewById(R.id.btn_listener1);

동시에 setOnClickListener를 이용하여 onClick() 이번트를 부여합니다.

버튼 클릭시 Toast를 이용하여 간단한 메시지를 보여 줍니다.


btnListener1.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Toast.makeText(MainActivity.this, "Listener Button1", Toast.LENGTH_SHORT).show();
}
});

버튼에 setOnclickListener를 설정할 때 자세히 보면

new View.OnClickListener() 이렇게 되어 있습니다.

new를 사용해서 각 버튼 별로 새로운 객체가 생성되어 작동을 합니다.

다른 버튼들이 getId()를 이용하여 버튼을 구분 하지만 이 버튼은 각자 별도의 객체로 작동이 됩니다.

 

3. 결과


3개의 버튼이 구현되었고 버튼 클릭시 메시지가 나타납니다.


android button



4. Source Code

 

4.1 activity_main.xml


layout에 버튼 3개를 정의 합니다.


<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout 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"
    tools:context=".MainActivity">

    <Button
        android:id="@+id/btn_listener1"
        android:text="@string/btn_listen1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginLeft="10dp"
        android:layout_marginTop="100dp"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

    <Button
        android:id="@+id/btn_listener2"
        android:text="@string/btn_listen2"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginLeft="130dp"
        android:layout_marginTop="100dp"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

    <Button
        android:id="@+id/btn_listener3"
        android:text="@string/btn_listen3"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginLeft="250dp"
        android:layout_marginTop="100dp"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

</android.support.constraint.ConstraintLayout>

4.2 strings.xml


button에 사용되는 text를 정의 합니다.


<resources>
    <string name="app_name">ButtonClickListener</string>
    <string name="btn_listen1">Listener1</string>
    <string name="btn_listen2">Listener2</string>
    <string name="btn_listen3">Listener3</string>
</resources>

4.3 MainActivity.java


버튼 생성과 동시에 이벤트를 등록하는 코드와 기능 구현이 포함 됩니다.


package copycoding.android.buttonclicklistener;

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;

public class MainActivity extends AppCompatActivity {

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

        // 2. Button 생성시 OnClickListner 구현 하는 방법
        Button btnListener1 = (Button)findViewById(R.id.btn_listener1);
        Button btnListener2 = (Button)findViewById(R.id.btn_listener2);
        Button btnListener3 = (Button)findViewById(R.id.btn_listener3);
        btnListener1.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Toast.makeText(MainActivity.this, "Listener Button1", Toast.LENGTH_SHORT).show();
            }
        });

        btnListener2.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Toast.makeText(MainActivity.this, "Listener Button2", Toast.LENGTH_SHORT).show();
            }
        });

        btnListener3.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Toast.makeText(MainActivity.this, "Listener Button3", Toast.LENGTH_SHORT).show();
            }
        });
    }
}


다른 버튼 사용 관련 참조


[android] 안드로이드 버튼(1) onClick() 함수 사용 방법

[android] 안드로이드 버튼(3) OnClickListener 인터페이스 구현 방법

[android] 안드로이드 버튼(4) OnClickListener 객체로 선언하여 구현하는 방법

[android] 안드로이드 버튼(5) 버튼 생성 모음 이미지 버튼


- copy coding -


 

여기에서 사용하는 onClick()public static final int onClick() 으로 R.asst에 속한 method 입니다.

다른 버튼에서 사용하는 onClick()public abstract void onClick (View v)으로 public static interface View.OnClickListener에 속해 있습니다.

android:onClick=”btnClick”의 형태로 layout 설정 xml에 추가 되어 View에서 클릭 되었을 때 정의된 이름의 함수를 호출하여 작동 합니다.

Activitypublic void btnClick(View v)으로 method를 선언 하지 않으면 오류가 발생 합니다.

Activitybutton을 생성하지 않고도 함수만 생성하여 호출 할 수 있습니다.

 

1. Layout에 이벤트 추가


activity_main.xmlLayout을 구성 하면서 Button에 이벤트를 등록 합니다.

android:onClick="btnClick” 이런 형태로 btnClick이건 java에서 사용할 함수 명으로 하시면 됩니다.

버튼을 클릭 하면 해당하는 btnClick() 함수를 찾아 실행을 하게 됩니다.


<Button
   
android:id="@+id/btn_onclick1"
   
android:text="@string/btn_click1"
   
android:layout_width="wrap_content"
   
android:layout_height="wrap_content"
   
android:layout_marginLeft="10dp"
   
android:layout_marginTop="50dp"
   
app:layout_constraintLeft_toLeftOf="parent"
   
app:layout_constraintTop_toTopOf="parent"
   
android:onClick="btnClick"/>


테스트를 위해 3개의 버튼을 만들고 3개 모두 동일한 android:onClick="btnClick” 이번트가 발생하도록 했습니다.

 

 

2. Activity에 기능 구현

 

버튼 클릭에 대한 함수를 구현 합니다.

public void btnClick(View view) { }

버튼 3개가 모두 동일한 btnClick() 함수를 호출 하도록 되어 있어 실제 어떤 버튼이 선택 되었는지는

getId()를 이용하여 ID를 확인 하고 그에 따라 작업을 분기 시킵니다.

if(view.getId() == R.id.btn_onclick1) { }

여기서는 Toast로 간단한 메시지를 보여 줍니다.

 


3. 결과


화면 버튼 구성이 좀 엉성하지만 3개의 버튼을 클릭하면 결과는 확인 가능 합니다.


angular icon onclick



4. Source Code

 

4.1 activity_main.xml


화면 구성 layout에 버튼 3개를 추가 합니다.


<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout 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"
    tools:context=".MainActivity">

    <Button
        android:id="@+id/btn_onclick1"
        android:text="@string/btn_click1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginLeft="10dp"
        android:layout_marginTop="50dp"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        android:onClick="btnClick"/>

    <Button
        android:id="@+id/btn_onclick2"
        android:text="@string/btn_click2"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginLeft="100dp"
        android:layout_marginTop="50dp"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        android:onClick="btnClick"/>

    <Button
        android:id="@+id/btn_onclick3"
        android:text="@string/btn_click3"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginLeft="200dp"
        android:layout_marginTop="50dp"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        android:onClick="btnClick"/>

</android.support.constraint.ConstraintLayout>


4.2 strings.xml


layout button에 사용되는 text를 정의 합니다.


<resources>
    <string name="app_name">ButtonOnClick</string>
    <string name="btn_click1">onClick1</string>
    <string name="btn_click2">onClick2</string>
    <string name="btn_click3">onClick3</string>
</resources>

4.3 MainActivity.java


Button Click시 호출 되는 함수를 기술 합니다.


public class MainActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
    }
    // Layout 작성시 button 속성에 onClick 이벤트를 준 경우
    public void btnClick(View view) {
        if(view.getId() == R.id.btn_onclick1) {  // Buttoon의 ID를 찾아서 실행이 된다.
            Toast.makeText(this, "onClick Button1", Toast.LENGTH_SHORT).show();
        } else if(view.getId() == R.id.btn_onclick2) {
            Toast.makeText(this, "onClick Button2", Toast.LENGTH_SHORT).show();
        } else if(view.getId() == R.id.btn_onclick3) {
            Toast.makeText(this, "onClick Button3", Toast.LENGTH_SHORT).show();
        }
    }
}

다른 버튼 사용 관련 참조


[android] 안드로이드 버튼(2) 생성시 OnClickListener 구현 방법

[android] 안드로이드 버튼(3) OnClickListener 인터페이스 구현 방법

[android] 안드로이드 버튼(4) OnClickListener 객체로 선언하여 구현하는 방법

[android] 안드로이드 버튼(5) 버튼 생성 모음 이미지 버튼


- copy coding -


안드로이드 스튜디오에서 앱을 만들고 테스트를 하기 위해 AVD Manager로 새로운 virtual device를 생성 했는데 에뮬레이터가 나타나지 않고 Emulator: emulator: ERROR: x86 emulation currently requires hardware acceleration! 오류가 발생하는 경우가 있습니다.


android emulation error


emulator에서 Nexus 6P API 28을 선택하고 [OK] 버튼을 틀릭 합니다.


잠시 후 하단과 같은 오류가 나타나고 작업이 중단 됩니다.



오류 내용은

Emulator: emulator: ERROR: x86 emulation currently requires hardware acceleration!

입니다.


해결 방법



1. Intel x86 Emulator Accelerator (HAXM installer) 설치


settings 팝업 창에서 작업을 하는데 팝업 창을 여는 방법은 2가지가 있습니다.

첫째는 상단메뉴 에서 Tool을 찾습니다.


Tools > SDK Manager



SDK Manager 메뉴를 선택 하면 Settings 팝업이 나옵니다.

 

두번째는 상단 메뉴에서 File을 찾습니다.


File > Settings


두가지 방법 모두 아래 Default Settings 팝업을 띄웁니다.

그림을 보면 알 수 있겠지만 다음을 선택


Appearance & Behavior > System Settings > Android SDK


하면 우측에 3개의 탭이 나오는데 그중에 SDK Tools를 선택 합니다.



 

설치가 안되어 있으면 설치를 합니다.

저는 이미 설치된 상태 인데도 emulator가 작동을 하지 않는 경우 입니다.

 

2. 프로그램 수동 실행


프로그램이 설치된 위치로 이동하여 수동으로 실행 시켜 줍니다.

위치는 개인별로 다를 텐데 기본 설치를 했다면 컴퓨터이름만 자신의 컴퓨터 이름으로 변경 합니다.


C:\Users\컴퓨터이름\AppData\Local\Android\Sdk\extras\intel\Hardware_Accelerated_Execution_Manager

 

못칮겠나요?

그럼 위의 사진에 Android SDK Location을 보시면 기본 디렉토리가 있습니다.

거기에 다음 위치를 연결하면 찾을 수 있습니다.

\extras\intel\Hardware_Accelerated_Execution_Manager

 

디렉토리에 파일들이 나옵니다.

이중에서 intelhaxm-android.exe 파일을 실행 합니다.



 

설치 과정은 단순하게 활성화 되어있는 버튼을 클릭하면 됩니다.



[Install] 버튼 클릭





[Finish] 버튼 클릭




이제 다시 emulator를 실행해 봅니다.



잘 실행이 되는 군요.




3. Windows 하이퍼바이저 플랫폼


Windows 하이퍼바이저 플랫폼을 체크해 주어야 한다는 이야기도 있는데 컴퓨터 마다 설정이 달라서 인듯 합니다.

저는 Windows 하이퍼바이저 플랫폼이 체크 안되어 있어도 잘되는 군요.

 

Windows 하이퍼바이저 플랫폼 설정 방법은

제어판에서 Windows 기능 켜기/끄기를 검색합니다. Windows를 한글로 쓰면 안됨.



팝업에서 Windows 하아퍼바이저 플랫폼을 체크 합니다.



 

Windows 7에서는 하이퍼바이저 오류는 없는것 같습니다.

한글 영문 검색을 해도 안나오는 군요.

 


 

따라 하기를 해도 나만 안될 때 참 비참한데...

그럴 때! 한번 더! 힘을 내시길 바랍니다.


- copy coding -


1. 프로젝트 생성

 

1.1 프로젝트 만들기

 

전에 google map을 사용할 수 있는 API key를 생성했는데요.


[안드로이드] google map 사용을 위한 API 생성(2018.11)


이제 키가 잘 작동 하는지 테스트를 해보겠습니다.

안드로이드 프로젝트를 하나 생성 합니다.


MapTest 이라는 이름으로 생성을 하겠습니다.


프로젝트 명을 입력하는 화면 하단에 Package name이 있습니다.

com.example.컴퓨터이름.프로젝트명 이런식으로 나타나는데 [Edit] 버튼을 누르면 편집이 가능 합니다.



필요하면 편집을 하고 [Done] 버튼을 누르면 반영이 됩니다.



com.android.google.maptest 이렇게 변경을 해 보았습니다.



Android 4.0으로 선택을 했는데 각자 알아서 선택을 하면 됩니다.



Empty Activity를 선택 합니다.



모두 기본으로 놓았는데 변경이 필요하면 수정 합니다.

이제 [Finish] 버튼을 눌러 프로젝트를 생성 합니다.

 

수정한 Package name으로 생성이 되었는지 확인해 볼까요?



잘 되어 있군요.

 

1.2 패키지 이름 등록

 

새로 만든 프로젝트에서 구글 맵을 사용 하려면 패키지 이름을 API 키에 등록해야 합니다.

google에 로그인을 하고 https://console.developers.google.com 에 접속 합니다.



사용자 인증 정보 만들기에서 API1을 선택 합니다. 등록할 때 이름을 변경 했다면 다른 이름이겠죠.

 

라디오 버튼 중 Android 앱을 선택합니다.

[+ 패키지 이름 및 지문 추가]를 선택하면 패키지 이름과 SHA-1 인증서 지문이 하나 추가 됩니다.



신규 생성한 내용을 추가 합니다.

빨간색 박스가 이번에 만든 패키지인증서 지문 입니다.

[저장] 버튼을 선택 하면 패키지 이름으로 생성된 프로젝트 에서 지도를 사용할 수 있습니다.

 


2. 프로젝트 개발

 

2.1 API 키 등록

 

구글 맵을 사용하기 위한 키를 등록 해야 권한을 이용 하여 앱에 지도가 표시 됩니다.


AndroidMainifest.xml


<meta-data
   
android:name="com.google.android.geo.API_KEY"
   
android:value="생성된 API 키 입력" />


2.2 Layout 작성

 

activity_main.xml


지도를 표시할 fragment 를 추가합니다.

그런데 빨간색으로 오류가 나오는 군요.

map 관련 class가 없어서 발생 하니 추가해야 합니다.



build.gradle

implementation 'com.google.android.gms:play-services:10.0.1'


를 추가 합니다.

그러면 상단에 Sync를 맞추라고 합니다. [Sync Now]를 클릭 합니다.



다시 activity_main.xml에 가봅니다.



빨간색이 없어졌습니다.



2.3 지도 사용

 

이제 지도를 그려 보겠습니다.

MainActivity.java implements OnMapReadyCallback를 이용해 보겠습니다.

 

onCreate()함수에 Fragment를 추가 하고


FragmentManager fragmentManager = getFragmentManager();
MapFragment mapFragment = (MapFragment)fragmentManager
        .findFragmentById(R.id.
map);
mapFragment.getMapAsync(this);


onMapReady() 함수에 지도를 그려줍니다OnMapReadyCallback이걸 추가하면 map 기능이 추가되어서 onMapReady() 함수에서 작업하면 됩니다.  이 함수에서 정거장 위치, 약속장소등을 어떻게 표시하는지 기회가 되면 설명 드리겠습니다.


@Override
public void onMapReady(final GoogleMap map) {

    LatLng SEOUL =
new LatLng(37.56, 126.97);

   
MarkerOptions markerOptions = new MarkerOptions();
   
markerOptions.position(SEOUL);
   
markerOptions.title("서울");
   
markerOptions.snippet("한국 수도");

   
map.addMarker(markerOptions);
   
map.moveCamera(CameraUpdateFactory.newLatLng(SEOUL));
   
map.animateCamera(CameraUpdateFactory.zoomTo(14));
}


실행을 해볼까요?

아직 오류가 발생합니다.

 

Error: Program type already present: android.support.v4.app.BackStackRecord$Op

 

android.support.v4 오류이군요.

gradle에 아래 내용을 추가 합니다.


implementation 'com.android.support:support-v4:27.1.0'


오류가 없어졌습니다.


왔다 갔다. 이것 저것 추가하고 혼란 스러운가요?


하단에 추가한 전체 소스가 그리 길지 않습니다.


전체 소스를 보면서 읽으면 별거 없습니다.



2.4  결과


android google map

 

이제 잘 나오는 군요.

지도의 좌표를 임의로 설정해서 나온 결과 입니다.

다음 번에는 핸드폰의 위치를 지도에 표시 해보도록 하겠습니다.

 

 

3. Source Code

 

3.1 AndroidManifest.xml


개인이 발급 받은 API 키 값을 넣으세요.

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

    <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">

        <meta-data
            android:name="com.google.android.geo.API_KEY"
            android:value="AIzxxxxx API 키 값xxxxxxxxxx_L8" />


        <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>


3.2 activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout 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"
    tools:context=".MainActivity">

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

</android.support.constraint.ConstraintLayout>

3.3 build.gradle

apply plugin: 'com.android.application'

android {
    compileSdkVersion 28
    defaultConfig {
        applicationId "com.android.google.maptest"
        minSdkVersion 14
        targetSdkVersion 28
        versionCode 1
        versionName "1.0"
        testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
    }
    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
    }
}

dependencies {
    implementation fileTree(dir: 'libs', include: ['*.jar'])
    implementation 'com.android.support:appcompat-v7:28.0.0'
    implementation 'com.android.support.constraint:constraint-layout:1.1.3'
    implementation 'com.google.android.gms:play-services:10.0.1'
    implementation 'com.android.support:support-v4:27.1.0'
    testImplementation 'junit:junit:4.12'
    androidTestImplementation 'com.android.support.test:runner:1.0.2'
    androidTestImplementation 'com.android.support.test.espresso:espresso-core:3.0.2'
}


3.4 MainActivity.java

package com.android.google.maptest;

import android.app.FragmentManager;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;

import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.MapFragment;
import com.google.android.gms.maps.OnMapReadyCallback;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.MarkerOptions;

public class MainActivity extends AppCompatActivity implements OnMapReadyCallback {

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

        FragmentManager fragmentManager = getFragmentManager();
        MapFragment mapFragment = (MapFragment)fragmentManager
                .findFragmentById(R.id.map);
        mapFragment.getMapAsync(this);

    }

    @Override
    public void onMapReady(final GoogleMap map) {

        LatLng SEOUL = new LatLng(37.56, 126.97);

        MarkerOptions markerOptions = new MarkerOptions();
        markerOptions.position(SEOUL);
        markerOptions.title("서울");
        markerOptions.snippet("한국 수도");

        map.addMarker(markerOptions);
        map.moveCamera(CameraUpdateFactory.newLatLng(SEOUL));
        map.animateCamera(CameraUpdateFactory.zoomTo(14));
    }

}

- copy coding -


1···105106107108109110111···119

+ Recent posts