위치 이동이 없는 경우 걸음 횟수를 계산하지 않는 방법을 질문하여 간단하게 테스트를 하여보았습니다.

기존에 올린 글 두개를 섞어서 만들어 보았습니다.


안드로이드 핸드폰 걸음 감지 센서 작동 테스트 (TYPE_STEP_DETECTOR)

안드로이드 GPS 이용한 속도 측정


소스는 간단 설명하면

1. 걸음 센서 작동 감지

2. 마지막 위치와 현재 위치 사이의 거리 계산

3. 일정 부분 움직인 경우만 걸음 수 계산

이렇게 됩니다.

 

조금씩 테스트 하면서 거리 값을 수정해야 할 것 같고 필요하면 시간도 포함을 하면 조금 좋은 걸음 수 계산을 할 수 있을 것 같습니다.


1. 걸음 센서 작동 감지 / 3. 걸음 수 계산


TYPE_STEP_DETECTOR가 감지되면 getGPSLocation() 함수를 호출 합니다.

if(longWork > 0.05) 테스트를 위해 거리 이동 감지를 0.05m로 했습니다.

0.05m 이상 이동하면 카운트를 하겠죠

@Override
public void onSensorChanged(SensorEvent event) {
    if(event.sensor.getType() == Sensor.TYPE_STEP_DETECTOR) {
        if(event.values[0] == 1.0f) {
            double longWork = getGPSLocation();
            if(longWork > 0.05) {
                mStepDetector++;
                tvStepDetector.setText("Step Detect : " + String.valueOf(mStepDetector));
                tvTimeDif.setText("Return 간격 : " + String.format("%.3f",longWork) + " m");  // Time Difference
            }
        }
    }
}


2. 마지막 위치와 현재 위치 사이의 거리 계산


최종 위치와 현재 위치를 이용하여 거리를 계산 합니다.

deltaDist = distance(lat1,  lng1,  lat2,  lng2);

 


4. 프로그램 소스

 

4.1 결과

 

걸음 감지가 되기 전에는 거리 계산을 하지 않아 모든 값이 공백입니다.

걸음이 감지 되면 기존 위치와 현재 위치를 이용하여 거리를 계산합니다.


step detector gps provider


핸드폰에서 직접 좌표이용 만보계를 테스트 해보세요.


StepLocation.apk




4.2 AndroidManifest.xml


위치 정보를 사용하기 위한 퍼미션 정보를 설정 합니다.


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

    <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
    <uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"/>

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


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

    <TextView
        android:id="@+id/tvTitle"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Step Detector Sensor"
        android:layout_marginTop="50dp"
        android:textSize="30dp"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

    <TextView
        android:id="@+id/tvGpsEnable"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="GPS Enable :"
        app:layout_constraintTop_toBottomOf="@+id/tvTitle"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        android:textSize="25dp"
        />

    <TextView
        android:id="@+id/tvStepDetector"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Step Detect : 0"
        app:layout_constraintTop_toBottomOf="@+id/tvGpsEnable"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        android:textSize="25dp"
        />

    <TextView
        android:id="@+id/tvGpsLatitude"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Start Latitude : "
        app:layout_constraintTop_toBottomOf="@+id/tvStepDetector"
        android:textSize="20dp"
        />
    <TextView
        android:id="@+id/tvGpsLongitude"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Start Longitude : "
        app:layout_constraintTop_toBottomOf="@+id/tvGpsLatitude"
        android:textSize="20dp"
        />
    <TextView
        android:id="@+id/tvEndLatitude"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="End Latitude : "
        app:layout_constraintTop_toBottomOf="@+id/tvGpsLongitude"
        android:textSize="20dp"
        />
    <TextView
        android:id="@+id/tvEndLongitude"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="End Longitude : "
        app:layout_constraintTop_toBottomOf="@+id/tvEndLatitude"
        android:textSize="20dp"
        />
    <TextView
        android:id="@+id/tvTimeDif"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="시간 간격 :"
        app:layout_constraintTop_toBottomOf="@+id/tvEndLongitude"
        android:textSize="25dp"
        />
    <TextView
        android:id="@+id/tvDistDif"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="거리 간격 :"
        app:layout_constraintTop_toBottomOf="@+id/tvTimeDif"
        android:textSize="25dp"
        />
    <TextView
        android:id="@+id/tvNowLatitude"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Now Latitude : "
        app:layout_constraintTop_toBottomOf="@+id/tvDistDif"
        android:textSize="20dp"
        />
    <TextView
        android:id="@+id/tvNowLongitude"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Now Longitude : "
        app:layout_constraintTop_toBottomOf="@+id/tvNowLatitude"
        android:textSize="20dp"
        />

</android.support.constraint.ConstraintLayout>


4.4 MainActivity.java


package copycoding.tistory.steplocation;

import android.Manifest;
import android.content.Context;
import android.content.pm.PackageManager;
import android.hardware.Sensor;
import android.hardware.SensorEvent;
import android.hardware.SensorEventListener;
import android.hardware.SensorManager;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.support.v4.app.ActivityCompat;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.widget.TextView;
import android.widget.Toast;

public class MainActivity extends AppCompatActivity implements SensorEventListener, LocationListener {

    private SensorManager sensorManager;
    private Sensor stepDetectorSensor;
    TextView tvStepDetector, tvGpsEnable, tvGpsLatitude, tvGpsLongitude, tvTimeDif, tvDistDif, tvEndLatitude, tvEndLongitude, tvNowLatitude, tvNowLongitude;
    private int mStepDetector = 0;
    private boolean isGPSEnable = false;

    private LocationManager locationManager;
    private Location lastKnownLocation = null;
    private Location nowLastlocation = null;

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

        //location -------
        tvGpsEnable = (TextView)findViewById(R.id.tvGpsEnable);
        tvGpsLatitude = (TextView)findViewById(R.id.tvGpsLatitude);
        tvGpsLongitude = (TextView)findViewById(R.id.tvGpsLongitude);
        tvEndLatitude = (TextView)findViewById(R.id.tvEndLatitude);
        tvEndLongitude = (TextView)findViewById(R.id.tvEndLongitude);
        tvNowLatitude = (TextView)findViewById(R.id.tvNowLatitude);
        tvNowLongitude = (TextView)findViewById(R.id.tvNowLongitude);
        tvTimeDif = (TextView)findViewById(R.id.tvTimeDif);
        tvDistDif = (TextView)findViewById(R.id.tvDistDif);
        //권한 체크
        if (ActivityCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
            return;
        }
        locationManager = (LocationManager)getSystemService(Context.LOCATION_SERVICE);
//        lastKnownLocation = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
        // GPS 사용 가능 여부 확인
        isGPSEnable = locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER);
        tvGpsEnable.setText("GPS Enable: " + isGPSEnable);  //GPS Enable
        locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, this);

        //step -----
        tvStepDetector = (TextView)findViewById(R.id.tvStepDetector);
        sensorManager = (SensorManager)getSystemService(Context.SENSOR_SERVICE);
        stepDetectorSensor = sensorManager.getDefaultSensor(Sensor.TYPE_STEP_DETECTOR);
        if(stepDetectorSensor == null) {
            Toast.makeText(this, "No Step Detect Sensor", Toast.LENGTH_SHORT).show();
        }
    }

    @Override
    public void onSensorChanged(SensorEvent event) {
        if(event.sensor.getType() == Sensor.TYPE_STEP_DETECTOR) {
            if(event.values[0] == 1.0f) {
                double longWork = getGPSLocation();
                if(longWork > 0.05) {
                    mStepDetector++;
                    tvStepDetector.setText("Step Detect : " + String.valueOf(mStepDetector));
                    tvTimeDif.setText("Return 간격 : " + String.format("%.3f",longWork) + " m");  // Time Difference
                }
            }
        }
    }

    public double getGPSLocation() {
        double deltaTime = 0.0;
        double deltaDist = 0.0;
        //GPS Start
        if(isGPSEnable) {
            if (ActivityCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
                return 0.0;
            }
//            lastKnownLocation = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
            if(lastKnownLocation == null ) {
                lastKnownLocation = nowLastlocation;
            }

            if (lastKnownLocation != null && nowLastlocation != null) {
                double lat1 = lastKnownLocation.getLatitude();
                double lng1 = lastKnownLocation.getLongitude();
                double lat2 = nowLastlocation.getLatitude();
                double lng2 = nowLastlocation.getLongitude();

                deltaTime = (nowLastlocation.getTime() - lastKnownLocation.getTime()) / 1000.0;  //시간 간격


                //double distanceMeter = distance(37.52135327,  126.93035147,  37.52135057,  126.93036593);
                deltaDist = distance(lat1,  lng1,  lat2,  lng2);
                if(deltaDist > 0.05) {
                    tvGpsLatitude.setText("Start Latitude : " + lat1);
                    tvGpsLongitude.setText("Start Longitude : " + lng1);
                    tvEndLatitude.setText("End Latitude : " + lat2);
                    tvEndLongitude.setText("End Longitude : " + lng2);
                    tvDistDif.setText("거리 간격 : " +  Double.parseDouble(String.format("%.3f",deltaDist)) + " m");  // Dist Difference
                    lastKnownLocation = nowLastlocation;
                    return deltaDist;
                }
//                lastKnownLocation = nowLastlocation;
            }
        }
        return 0.0;
    }

    @Override
    public void onLocationChanged(Location location) {
        nowLastlocation = location;
        Toast.makeText(this, "Locatiuon Changed", Toast.LENGTH_SHORT).show();
        double lng = location.getLongitude();
        double lat = location.getLatitude();
        Log.d("Now Location ::::::", "longtitude=" + lng + ", latitude=" + lat);
        tvNowLatitude.setText("Now Latitude : " + lat);
        tvNowLongitude.setText("Now Longitude : " + lng);
    }


    @Override
    public void onProviderEnabled(String provider) {
        //권한 체크
        if (ActivityCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
            return;
        }
        // 위치정보 업데이트
        locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0,0, this);
    }

    @Override
    protected void onResume() {
        super.onResume();
        sensorManager.registerListener(this, stepDetectorSensor, SensorManager.SENSOR_DELAY_UI);

        //권한 체크
        if (ActivityCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
            return;
        }
        // 위치정보 업데이트
        locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0,0, this);
    }

    @Override
    protected void onPause() {
        super.onPause();
        sensorManager.unregisterListener(this);

        // 위치정보 가져오기 제거
        locationManager.removeUpdates(this);
    }

    @Override
    protected void onStart() {
        super.onStart();

        if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED
                && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
            //권한이 없을 경우 최초 권한 요청 또는 사용자에 의한 재요청 확인
            if (ActivityCompat.shouldShowRequestPermissionRationale(this, Manifest.permission.ACCESS_FINE_LOCATION) &&
                    ActivityCompat.shouldShowRequestPermissionRationale(this, Manifest.permission.ACCESS_COARSE_LOCATION)) {
                // 권한 재요청
                ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.ACCESS_FINE_LOCATION, Manifest.permission.ACCESS_COARSE_LOCATION}, 100);
                return;
            } else {
                ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.ACCESS_FINE_LOCATION, Manifest.permission.ACCESS_COARSE_LOCATION}, 100);
                return;
            }
        }
    }

    @Override
    public void onAccuracyChanged(Sensor sensor, int accuracy) {

    }

    @Override
    public void onProviderDisabled(String provider) {

    }

    @Override
    public void onStatusChanged(String provider, int status, Bundle extras) {

    }

    // 거리계산
    private static double distance(double lat1, double lon1, double lat2, double lon2) {

        double theta = lon1 - lon2;
        double dist = Math.sin(deg2rad(lat1)) * Math.sin(deg2rad(lat2)) + Math.cos(deg2rad(lat1)) * Math.cos(deg2rad(lat2)) * Math.cos(deg2rad(theta));

        dist = Math.acos(dist);
        dist = rad2deg(dist);
        dist = dist * 60 * 1.1515;
        dist = dist * 1.609344 * 1000; //미터 단위

        return dist;
    }


    // This function converts decimal degrees to radians
    private static double deg2rad(double deg) {
        return (deg * Math.PI / 180.0);
    }

    // This function converts radians to decimal degrees
    private static double rad2deg(double rad) {
        return (rad * 180 / Math.PI);
    }


}

- copy coding -


핸드폰을 교체할 때 유심칩을 갈아 끼우면 주소록등은 그대로 넘어 가는데 기존에 설치해 놓은 앱들은

하나도 설치가 되지 않는 경우가 있습니다.

 

안드로이드는 앱을 설치 하려면 play store를 통해야 하고 play store google에 로그인을 해야 사용이 가능 합니다.

, 모든 앱 설치 정보가 play store에 기록으로 남아 있다는 얘기 이므로 기존에 사용하던 앱을 쉽게 설치가 가능 합니다.

 

1. Play 스토어 앱 실행



play 스토어 앱을 실행 합니다.


 

2. 상단 줄3개 클릭

 

상단에 있는 줄3개를 클릭 하면 하부 메뉴가 나타 납니다.

 



3. 내 앱/게임



좌측 메뉴에서 [내 앱/게임]을 선택 하면 play 스토어에서 설치한 앱이 잘 정리 되어 있습니다.

 


4. 업데이트


업데이트 항목에서는 현재 스마트폰의 앱 상태를 볼 수 있습니다.


 

 

5. 설치됨


현재 스마트폰에 설치되어 있는 앱 리스트를 보여 줍니다.



 

6. 라이브러리


기존에 한번이라도 설치를 했던 앱 리스트가 나옵니다.

현재는 삭제를 하고 사용하지 않는 앱들도 리스트에 들어 있습니다.


android app install

 

하나씩 필요한 앱을 설치해줍니다.

설치를 하면 라이브러 리스트에서는 사라집니다.


- copy coding -


앞에서 설명한 버튼 사용법 4가지를 하나의 프로젝트에 포함시켜 보았습니다.

그리고 이미지를 이용한 버튼 생성도 추가를 했습니다.

 

사용된 layout 구성은 ConstraintLayout 을 이용 하였고 버튼 위치는 editor가 아닌 수작업으로 위치를 표시 하였습니다.

 

1. 버튼 위치 잡기


1.1 text button


app:layout_constraintTop_toTopOf="parent" – 이걸로 위쪽 기준을 잡아줍니다.

android:layout_marginTop="76dp" – 위에서 잡은 기준으로 부터 76dp 떨어진 위치에서 시작합니다.


그럼 좌측도 동일하게

app:layout_constraintLeft_toLeftOf="parent" – 이걸로 좌측 기준을 정해야 합니다.

android:layout_marginLeft="50dp"  - 정해진 좌측 기준으로 부터 50dp 만큼 떨어진 위치에서 시작..

 

 

1.2 Image button


app:layout_constraintLeft_toLeftOf="parent"  - image도 동일하게 기준을 잡아 줍니다.

android:layout_marginTop="450dp" – 잡아준 기준으로 부터의 거리에 image를 위치 합니다.

android:src="@drawable/battery_charging_18dp" – 이건 이미지 위치

android:padding="0dp" – 이미지 여백. 0이면 여백이 없어 이미지 자체가 여백이 있어야 한다.

 

 

2. 이미지 버튼

 

2.1 이미지 + 텍스트

 

android:drawableXXX를 이용하여 구현해 보았습니다.

drawableLeft, drawableRight, drawableTop... 등등이 있으니 필요한 기능을 사용해 봅시다.

 

2.2 이미지 버튼

 

<ImageButton /> 태그를 이용하여 이미지 위치(android:src="@drawable/battery_charging_btn")를 정해 줍니다.

 

 

3. 기존 구현 버튼 모음

 

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

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

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

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


4. Source Code

 

4.1 결과 화면


android img button


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

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

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

    <Button
        android:id="@+id/btn_implements1"
        android:text="@string/btn_implement1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginLeft="5dp"
        android:layout_marginTop="150dp"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintTop_toTopOf="parent" />
    <Button
        android:id="@+id/btn_implements2"
        android:text="@string/btn_implement2"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginLeft="125dp"
        android:layout_marginTop="150dp"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintTop_toTopOf="parent" />
    <Button
        android:id="@+id/btn_implements3"
        android:text="@string/btn_implement3"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginLeft="245dp"
        android:layout_marginTop="150dp"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

    <Button
        android:id="@+id/btn_object1"
        android:text="@string/btn_object1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginLeft="20dp"
        android:layout_marginTop="200dp"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintTop_toTopOf="parent" />
    <Button
        android:id="@+id/btn_object2"
        android:text="@string/btn_object2"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginLeft="140dp"
        android:layout_marginTop="200dp"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintTop_toTopOf="parent" />
    <Button
        android:id="@+id/btn_object3"
        android:text="@string/btn_object3"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginLeft="260dp"
        android:layout_marginTop="200dp"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

    <Button
        android:id="@+id/btn_imgtext"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginLeft="88dp"
        android:layout_marginTop="250dp"
        android:paddingRight="40dp"
        android:drawableLeft="@drawable/battery_charging"
        android:drawableRight="@drawable/battery_charging"
        android:drawableTop="@drawable/battery_charging"
        android:drawableBottom="@drawable/battery_charging"
        android:text="@string/btn_img_text"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

    <ImageButton
        android:id="@+id/btn_img"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginLeft="160dp"
        android:layout_marginTop="330dp"
        android:padding="0dp"
        android:src="@drawable/battery_charging_btn"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

</android.support.constraint.ConstraintLayout>


4.3 strings.xml


<resources>
    <string name="app_name">ButtonTest</string>
    <string name="btn_click1">onClick1</string>
    <string name="btn_click2">onClick2</string>
    <string name="btn_click3">onClick3</string>
    <string name="btn_listen1">Listener1</string>
    <string name="btn_listen2">Listener2</string>
    <string name="btn_listen3">Listener3</string>
    <string name="btn_implement1">Implement1</string>
    <string name="btn_implement2">Implement2</string>
    <string name="btn_implement3">Implement3</string>
    <string name="btn_object1">Object1</string>
    <string name="btn_object2">Object2</string>
    <string name="btn_object3">Object3</string>
    <string name="btn_img_text">Image Text Button</string>
</resources>


4.4 drawable image



버튼에 사용한 이미지






4.5 MainActivity.java


package com.example.desk.buttontest;

import android.content.Context;
import android.graphics.drawable.Drawable;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.Toast;

public class MainActivity extends AppCompatActivity
        implements Button.OnClickListener // 3. implements 구현 방법
{
    // 4. OnClickListener를 객체로 만드는 방법
    Button.OnClickListener btnObject = new View.OnClickListener() {
        public void onClick(View v) {
            if(v.getId() == R.id.btn_object1) {
                Toast.makeText(MainActivity.this, "Object Button1", Toast.LENGTH_SHORT).show();
            } else if(v.getId() == R.id.btn_object2) {
                Toast.makeText(MainActivity.this, "Object Button2", Toast.LENGTH_SHORT).show();
            } else if(v.getId() == R.id.btn_object3) {
                Toast.makeText(MainActivity.this, "Object Button3", Toast.LENGTH_SHORT).show();
            }
        }
    };

    @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();
            }
        });

        // 3. MainActivity에 implements View.OnClickListener를 이용한 경우
        Button btnImplement1 = (Button)findViewById(R.id.btn_implements1);
        Button btnImplement2 = (Button)findViewById(R.id.btn_implements2);
        Button btnImplement3 = (Button)findViewById(R.id.btn_implements3);
        btnImplement1.setOnClickListener(this);
        btnImplement2.setOnClickListener(this);
        btnImplement3.setOnClickListener(this);
        //image button
        Button btnImgtext = (Button)findViewById(R.id.btn_imgtext);
        ImageButton btnImg = (ImageButton) findViewById(R.id.btn_img);
        btnImgtext.setOnClickListener(this);
        btnImg.setOnClickListener(this);

        // 4. OnClickListener를 객체로 만드는 방법
        findViewById(R.id.btn_object1).setOnClickListener(btnObject);
        findViewById(R.id.btn_object2).setOnClickListener(btnObject);
        findViewById(R.id.btn_object3).setOnClickListener(btnObject);
    }

    // 1. onClick 함수를 호출 하는 방법 (activity_main.xml)
    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();
        }
    }

    // 3. MainActivity에 implements View.OnClickListener를 이용한 경우
    @Override
    public void onClick(View v) {
        if(v.getId() == R.id.btn_implements1) {
            Toast.makeText(MainActivity.this, "implements Button1", Toast.LENGTH_SHORT).show();
        } else if(v.getId() == R.id.btn_implements2) {
            Toast.makeText(MainActivity.this, "implements Button2", Toast.LENGTH_SHORT).show();
        } else if(v.getId() == R.id.btn_implements3) {
            Toast.makeText(MainActivity.this, "implements Button3", Toast.LENGTH_SHORT).show();
        } else if(v.getId() == R.id.btn_imgtext) {
            Toast.makeText(MainActivity.this, "Image Text Button", Toast.LENGTH_SHORT).show();
        } else if(v.getId() == R.id.btn_img) {
            Toast.makeText(MainActivity.this, "Image Button", Toast.LENGTH_SHORT).show();
        }
    }
}

- copy coding -


Button.OnClickListener 객체를 생성하여 .버튼에 설정 해주는 방식입니다.

버튼 오브젝트를 생성하고

Button.OnClickListener btnObject = new View.OnClickListener(){public void onClick(View v){}};

이걸 callback으로 이용해서 버튼을 정의 합니다.

 

1. Layout에 이벤트 추가


activity_main.xmlButtonLayout을 구성 합니다.


<Button
android:id="@+id/btn_object1"
android:text="@string/btn_object1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="20dp"
android:layout_marginTop="200dp"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintTop_toTopOf="parent" />


3개의 버튼을 만들어서 테스트를 진행 합니다..

 

2. Activity에 기능 구현

 

Button.OnClickListener 객체를 생성 하고 각 버튼 클릭시 간단한 메시지를 보여주도록 합니다.


Button.OnClickListener btnObject = new View.OnClickListener() {
public void onClick(View v) {
if(v.getId() == R.id.btn_object1) {
Toast.makeText(MainActivity.this, "Object Button1", Toast.LENGTH_SHORT).show();
} else if(v.getId() == R.id.btn_object2) {
Toast.makeText(MainActivity.this, "Object Button2", Toast.LENGTH_SHORT).show();
} else if(v.getId() == R.id.btn_object3) {
Toast.makeText(MainActivity.this, "Object Button3", Toast.LENGTH_SHORT).show();
}
}
};

onCreate()에서 버튼에 생성된 Button.OnClickListener 객체를 대입해 줍니다.


findViewById(R.id.btn_object1).setOnClickListener(btnObject);
findViewById(R.id.btn_object2).setOnClickListener(btnObject);
findViewById(R.id.btn_object3).setOnClickListener(btnObject);


3. 결과


버튼 3개가 구현되고 선택을 하면 해당 메시지가 나타납니다.


android button onclicklistener



4. Source Code

 

4.1 activity_main.xml


버튼 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_object1"
        android:text="@string/btn_object1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginLeft="20dp"
        android:layout_marginTop="200dp"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

    <Button
        android:id="@+id/btn_object2"
        android:text="@string/btn_object2"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginLeft="140dp"
        android:layout_marginTop="200dp"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

    <Button
        android:id="@+id/btn_object3"
        android:text="@string/btn_object3"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginLeft="260dp"
        android:layout_marginTop="200dp"
        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">Button Object</string>
    <string name="btn_object1">Object1</string>
    <string name="btn_object2">Object2</string>
    <string name="btn_object3">Object3</string>
</resources>


4.3 MainActivity.java


package copycoding.button.object.buttonobject;

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 {

//    Button.OnClickListener btnObject = new View.OnClickListener(){public void onClick(View v){}};
    // 4. OnClickListener를 객체로 만드는 방법
    Button.OnClickListener btnObject = new View.OnClickListener() {
        public void onClick(View v) {
            if(v.getId() == R.id.btn_object1) {
                Toast.makeText(MainActivity.this, "Object Button1", Toast.LENGTH_SHORT).show();
            } else if(v.getId() == R.id.btn_object2) {
                Toast.makeText(MainActivity.this, "Object Button2", Toast.LENGTH_SHORT).show();
            } else if(v.getId() == R.id.btn_object3) {
                Toast.makeText(MainActivity.this, "Object Button3", Toast.LENGTH_SHORT).show();
            }
        }
    };

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

        // 4. OnClickListener를 객체로 만드는 방법
        findViewById(R.id.btn_object1).setOnClickListener(btnObject);
        findViewById(R.id.btn_object2).setOnClickListener(btnObject);
        findViewById(R.id.btn_object3).setOnClickListener(btnObject);
    }
}


다른 버튼 사용 관련 참조


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

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

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

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


- copy coding -


1···101112131415

+ Recent posts