안드로이드 디바이스가 안드로이드 스튜디오에서 run을 눌렀을때 안보이는경우

많이 당황하셨지요?



자 하나하나 체크해봅시다.


1. USB케이블 

USB케이블로 디바이스를 연결했을때 windows 환경에서 팝업이뜨나요? 윈도우 탐색기에서 폰으로 들어갈수있나요?

들어갈수있다면 OK 안들어가지고 그냥 충전중만 뜬다면 주변에 다른케이블로 시도를 해보세요.



2. USB 드라이버

폰 기종별로 USB드라이버가 있습니다.

저의경우 S7인데 통합 usb드라이버를 찾았어요


3. 개발자모드 활성화, USB디버깅 활성화

설정 > 디바이스정보 > 소프트웨어 정보 > 빌드번호 여러번 누르면 개발자모드가 활성화 됩니다.


개발자 옵션 > usb디버깅 on 


자 이래도 안되신다 다른 블로그를 찾아주세요

Posted by App.SHIN
:

안녕하세요 오늘은 GCM 을 정리하려다 GCM 사이트를 들어가보니 FCM을 추천을 하고있어서

FCM으로 Android Push Message를 해보려고 합니다.



Firebase Cloud Messaging (FCM) is the new version of GCM. It inherits the reliable and scalable GCM infrastructure, plus new features! See the FAQ to learn more. If you are integrating messaging in a new app, start with FCM. GCM users are strongly recommended to upgrade to FCM, in order to benefit from new FCM features today and in the future.



https://firebase.google.com/docs/cloud-messaging/android/client



예제로 제공되는 프르젝트 입니다. 

https://github.com/firebase/quickstart-android/tree/master/messaging


<사전작업>

https://console.firebase.google.com/?hl=ko

프로젝트를 생성하시고 

새프로젝트 만들기 선택후 

Android package name 부분에는 

(패키지 이름은 보통 앱 수준 build.gradle 파일의 applicationId입니다.)


저의 경우는 com.example.john.fcmtest 입니다. 












전체적인 구성도는 아래와같습니다.


휴대폰에서 FCM 토큰을 생성하여 개인 서버로 전송을 합니다.

그리고 개인서버에는 그 토큰이 저장이 되어있고,


그뒤에 관리자가 push메시지를 보내야할때 서버에 저장이 되어있는 토큰을 이용하여

FCM 쪽으로 푸시요청을 합니다.


그럼 FCM 에서 해당토큰의 단말로 푸시메시지를 보냅니다.







사이트는 깔끔하고 한글화 도 잘되어있네요.

우선 프로젝트를 생성합니다.



한동안 android app을 안했는데 이제 분위기가 

eclipse plugin 은 안쓰는 분위기고 Android Studio 를 사용하고  bulid 툴로는 gradle을 기본적으로 쓰는 가이드가 나오기때문에

저도 안드로이드 개발할때는 eclipse 를 안쓰고 Android Studio를 사용하도록 할예정입니다.



우선 프로젝트를 만들었습니다.

처음으로 할일은 project gradle에 classpath를 추가합니다.

그리고 run 을 누릅니다.

// Top-level build file where you can add configuration options common to all sub-projects/modules.

buildscript {
repositories {
jcenter()
}
dependencies {
classpath 'com.android.tools.build:gradle:2.2.3'
classpath 'com.google.gms:google-services:3.0.0'
// NOTE: Do not place your application dependencies here; they belong
// in the individual module build.gradle files
}
}

allprojects {
repositories {
jcenter()
}
}

task clean(type: Delete) {
delete rootProject.buildDir
}

run 을 수행하면 콘솔창에 아래처럼 빌드 잘되었다고 뜹니다.


BUILD SUCCESSFUL


Total time: 7.069 secs


Process finished with exit code 0



그런뒤 app bulid.gradle에 추가를 합니다.


마찬가리로 run을 눌러 success 가 되는것을 확인한뒤 manifest.xml에 service를등록합니다.



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

<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:supportsRtl="true"
android:theme="@style/AppTheme">
<activity
android:name=".MainActivity"
android:label="@string/app_name"
android:theme="@style/AppTheme.NoActionBar">
<intent-filter>
<action android:name="android.intent.action.MAIN" />

<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<service
android:name=".MyFirebaseMessagingService">
<intent-filter>
<action android:name="com.google.firebase.MESSAGING_EVENT"/>
</intent-filter>
</service>

<service
android:name=".MyFirebaseInstanceIDService">
<intent-filter>
<action android:name="com.google.firebase.INSTANCE_ID_EVENT"/>
</intent-filter>
</service>

</application>

</manifest>

위에 코드처럼 <application> 태그 사이에 <service 부분을 넣습니다.

그리고 서비스를 만들어야겠죠?




class 를 추가합니다. 두가지 클래스를 만듭니다.


MyFirebaseMessagingService, MyFirebaseInstanceIDService를 생성하여  extends 합니다.


FirebaseMessagingService 와 FirebaseInstanceIdService 를 extends 합니다. 



package com.example.john.fcmtest;

import android.util.Log;

import com.google.firebase.iid.FirebaseInstanceId;
import com.google.firebase.iid.FirebaseInstanceIdService;

import java.io.IOException;

import okhttp3.FormBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;


/**
* Created by John on 2017-04-08.
*/

public class MyFirebaseInstanceIDService extends FirebaseInstanceIdService
{
String TAG = "AAAAA";
String strUrl;
String result;

@Override
public void onTokenRefresh() {
Log.d(TAG, "bbb" );


String refreshedToken = FirebaseInstanceId.getInstance().getToken();
Log.d(TAG, "Refreshed token: " + refreshedToken);

// If you want to send messages to this application instance or
// manage this apps subscriptions on the server side, send the
// Instance ID token to your app server.
sendRegistrationToServer(refreshedToken);
}
private void sendRegistrationToServer(String token) {
OkHttpClient client = new OkHttpClient();
RequestBody body = new FormBody.Builder()
.add("uid", "aa")
.add("id", token)
.build();

//request
Request request = new Request.Builder()
.url("http://서버/register.do")
.post(body)
.build();

try {
client.newCall(request).execute();
} catch (IOException e) {
e.printStackTrace();
}
}
}

public void onTokenRefresh() 는 단말접속을 하고 KCM 토큰이 생성되어있지않거나 리프레쉬될때 호출됩니다.

테스트 하실때는 앱을 삭제후 다시 설치하는 식으로 테스트하시기바랍니다.



package com.example.john.fcmtest;

import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.media.RingtoneManager;
import android.net.Uri;
import android.support.v4.app.NotificationCompat;

import com.google.firebase.messaging.FirebaseMessagingService;
import com.google.firebase.messaging.RemoteMessage;

/**
* Created by John on 2017-04-08.
*/

public class MyFirebaseMessagingService extends FirebaseMessagingService
{
@Override
public void onMessageReceived(RemoteMessage remoteMessage) {
sendNotification( remoteMessage.getData().get("msg"));
}

private void sendNotification(String messageBody) {
Intent intent = new Intent(this, MainActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
PendingIntent pendingIntent = PendingIntent.getActivity(this, 0 /* Request code */, intent,
PendingIntent.FLAG_ONE_SHOT);

Uri defaultSoundUri= RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(this)
.setSmallIcon(R.drawable.ic_menu_camera)
.setContentTitle("FCM Message")
.setContentText(messageBody)
.setAutoCancel(true)
.setSound(defaultSoundUri)
.setContentIntent(pendingIntent);

NotificationManager notificationManager =
(NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);

notificationManager.notify(0 /* ID of notification */, notificationBuilder.build());
}
}



여기까지만 하시면 완료되셨습니다.



그뒤에 앱을 실행시키고 로그에 찍히는 토큰을 저장해두었다가.


크롬 클라이언트 프로그램중에  postman을 이용하여 호출을 해봅니다.


header 부분에도 FCM에 요청하신부분을 채워넣습니다.


https://firebase.google.com/docs/cloud-messaging/send-message?hl=ko


to 뒷부분에 값으로 앱실행했을때 토큰값을 입력하시면됩니다.

https://fcm.googleapis.com/fcm/send
Content-Type:application/json
Authorization:key=AIzaSyZ-1u...0GBYzPu7Udno5aA

{ "data": {
   
"score": "5x1",
   
"time": "15:10"
 
},
 
"to" : "bk3RNwTe3H0:CI2k_HHwgIpoDKCIZvvDMExUdFQ3P1..."
}



key=등록된 서버 키


https://console.firebase.google.com/project/testaaa-ad72b/settings/cloudmessaging?hl=ko

에서 만들어둔 프로젝트의 서버 정보를 입력하시면됩니다.



클라우드 메시징 탭을 클릭하시면 서버키 부분이있습니다.












앱을 실행후 해당 메시지를 보내면 application부분에 보입니다.


잘못된점이나 문의사항있으시면 말씀해주세요~


Posted by App.SHIN
:

'd:skin' 요소로 시작하는 부적합한 콘텐츠가 발견되었습니다. 여기에는 하위 요소가 필요하지 않습니다.

라는 메시지가 콘솔에 붉은 글씨로 쭉 떠서 원인을 찾아보다가 해결책만 찾았습니다.

원인은 모르겠어요 ㅠㅠ


서포트 라이브러리 설치하면서 문제가 생긴거같습니다.

Android SDK Manager을 켜서  Android 5.1.1 ( API 22 ) 부분 설치된 목록에서 

아래 두개를 삭제합니다. 저같은경우에는 스택오버플로우에 나와있는데로 따라하니 되네요

관련 글 : http://stackoverflow.com/questions/30418443/android-sdk-error-when-loading-the-sdk




Posted by App.SHIN
:

3X3의 슬라이딩 퍼즐을 만들어봅니다.

강좌 6번의 뷰를 복사하여 CustomView를 하나더 만듭니다.

PuzzleView.java 와 SlidingPuzzleActivity를 만들었습니다.


기본적인 Idea는 2차원 배열을 만들고 

이동이되면 해당 배열을 계속해서 업데이트합니다.

그래고 2차원배열이 순서대로 되면 게임이 끝나는 것이 기본 idea입니다.


게임 2차원 배열을 만듭니다.

0

1

2

3

4

5

6

7

8

그리고 해당 내용에 대해 비트맵을 9개로 나누어 각각 가지고있습니다.

그리고 onDraw에서 각각의 퍼즐 블록을 그려주고 , 라인을 그려줍니다.

				    		  canvas.drawBitmap( mBitmapCube[i][j]
				    		   , mCubeRect[i][j].left
				    		   , mCubeRect[i][j].top
				    		   , paint);


그리고 각블록에 대해 Rect 정보를 가지고있습니다.

Rect는 left, right , top , bottom 값으로 사각형의 위치정보를 가지고있습니다.


Rect는 두가지로 mCubeOriginRect 원래위치 그리고 mCubeRect 

이번버전에는 빈칸이 위치한 부분에 대해서만 같은행 같은 열을 선택하였을떄 

해당 블록이 움직일수있게 처리해보았습니다.


클릭되었을경우 선택된 블록의 index 를 저장해둡니다.

				for( int i = 0 ; i < 3; i++ ) {
					for( int j = 0 ; j < 3 ; j++ ) {
						if( mCubeOriginRect[i][j].contains( startPoint.x , startPoint.y ) == false ) continue;
						
						mSelectedCubeHeightIndex = i;
						mSelectedCubeWidthIndex = j;
						invalidate();
						break;
					}
				}


그리고 MOVE이벤트가 발생했을경우 해당 CubeRect의 값을 바꿔줍니다.

	    		// 같은 행에 있으면
	    		if( mSpaceCubeHeightIndex ==  mSelectedCubeHeightIndex ) {
	    			int moveXpos = endPoint.x - startPoint.x;
	    			mCubeRect[mSelectedCubeHeightIndex][mSelectedCubeWidthIndex].left =
	    					mCubeOriginRect[mSelectedCubeHeightIndex][mSelectedCubeWidthIndex].left + moveXpos;
	    			mCubeRect[mSelectedCubeHeightIndex][mSelectedCubeWidthIndex].right = 
	    					mCubeOriginRect[mSelectedCubeHeightIndex][mSelectedCubeWidthIndex].right + moveXpos;
	    		}
	    		// 같은 열에 있으면
	    		if( mSpaceCubeWidthIndex ==  mSelectedCubeWidthIndex ) {
	    			int moveYpos = endPoint.y - startPoint.y;
	    			
	    			mCubeRect[mSelectedCubeHeightIndex][mSelectedCubeWidthIndex].top =
	    					mCubeOriginRect[mSelectedCubeHeightIndex][mSelectedCubeWidthIndex].top + moveYpos;
	    			mCubeRect[mSelectedCubeHeightIndex][mSelectedCubeWidthIndex].bottom = 
	    					mCubeOriginRect[mSelectedCubeHeightIndex][mSelectedCubeWidthIndex].bottom + moveYpos;
	    			
	    		}


실행화면


ShinExample_7.zip




Posted by App.SHIN
:

오늘은 커스텀 뷰를 만들고 Bitmap을 리소스로 부터 불러와서 표시합니다.

activity를 생성하고 layout에 커스텀 뷰를 설정하고 클래스를 만듭니다.

resource xml 설정

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
 		android:orientation="vertical"
 		android:layout_width="fill_parent"
 		android:layout_height="fill_parent"
 	>
<com.shin.view.CustomView
    android:id="@+id/custom_view"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    />
</LinearLayout>


CustomView를 Xml 파일에 입력을 했다면 변수가 필요합니다.

public CustomView(Context context,AttributeSet attrs)


bitmap = BitmapFactory.decodeResource(getResources(), R.drawable.ex1 );

이렇게 설정을하고 클래스 파일에서 리소스로 부터 Bitmap을 불러옵니다.


public CustomView(Context context,AttributeSet attrs) {
        super(context, attrs);
        orign = new Rect();
        dest = new Rect();
        
        bitmap = BitmapFactory.decodeResource(getResources(), R.drawable.ex1 );
        orign.left = 0;
        orign.right = bitmap.getWidth();
        orign.top = 0;
        orign.bottom = bitmap.getHeight();
        
        paint = new Paint();
        
	}

리소스파일

결과 화면

결과파일


ShinExample_06.zip



Posted by App.SHIN
:

안녕하세요 지난시간에 이어 계산하는 부분을 추가하는데요.


StringTokenizer 클래스를 사용합니다.


생성을 할때 내용과 딜리미터를 전달합니다.

예를 들어  내용이 A_B_C  딜리미터가 _ 라면 

StringTokenizer st = new StringTokenizer( "A_B_C" , "_" ); 

이렇게 사용하시면 됩니다. 게다가 딜리미터의경우 멀티로도 가능합니다. 

예를들면 StringTokenizer("A+B-C/D", "+-/") 이런 식으로 사용이가능하가는 거지요~

while( st.hasMoreTokens() ) {
          double number = Double.parseDouble(st.nextToken());
          numberList.add( number );
          Log.d("aaa", String.valueOf(number) );
}



계산기의 기본 아이디어를 설명드리겠습니다.


StringTokenizer로 숫자부분은 얻을수있습니다. 하지만  Operator( +-/* )는 얻을수가 없어요

그래서 숫자, 오퍼레이터는 내용에 추가합니다.


사용자가 1+1/10 이런식으로 입력했다면 TextView에 계속해서 추가해줍니다.

사용자가 오퍼레이터 입력시 operatorList 변수를 만들어 해당 operator를 저장시킵니다.


그리고 계산을 누르게되면 TextView 내용에대해 StringTokenizer를 이용하여 숫자부분만 뽑아냅니다.

그리고 Operator같은 경우는 정상적인 경우라면


만약 사용자가 10+20/30 을 입력했다면 OperatorList 와 NumberList는 아래와 같습니다.

OperatorList는 사용자가 기호를 입력할때마다 add 시켜주면 저렇게 입력이되구요

+입력될때 operatorList 에 입력 / 입력될때 입력이 됩니다.

NumberList는 StringTokenizer 를 이용하여 nextToken으로 값을 뽑아내면 아래와같이 입력됩니다.

 

사용자입력

10

+

20

/

30

OperatorList

0

1

 

 

 

+

/

 

 

 

NumberList

0

1

2

 

 

 

10

20

30

 

 

         








가. NumberList[0], NumberList[1] 에대해 OperatorList[0]계산 -> 10 , 20 에 대한 + 계산  => 30 

나. 가.의 결과 , NumberList[2] 에 대해 OperatorList[1]계산 -> 30 , 30 에 대한 / 계산 => 1

의 형식으로 됩니다.


아래는 Calc 함수내용입니다.


private String calc(String exp) {
		
		
		ArrayList<Double> numberList = new ArrayList<Double>();
		StringTokenizer st = new StringTokenizer(exp,"X/+-");
		
		
		while( st.hasMoreTokens() ) {
			double number = Double.parseDouble(st.nextToken());
			numberList.add( number );
			Log.d("aaa", String.valueOf(number) );
		}
		
		double result = numberList.get(0);
		Log.d("aaa", String.valueOf(result) );
		for( int i = 0 ; i < operatorList.size() ; i++ ) {
			String operator = operatorList.get(i);
			
			if( "*".equals(operator)){
				result = ( result * numberList.get(i+1));
			}else if( "/".equals(operator)){
				result = ( result / numberList.get(i+1));
			}else if( "+".equals(operator)){
				result = ( result + numberList.get(i+1));
			}else if( "-".equals(operator)){
				result = ( result - numberList.get(i+1));
			}
		}
		operatorList.clear();
		numberList.clear();
		
		return String.valueOf(result);
	}



ShinExample_05.zip


Posted by App.SHIN
:

오늘은 계산기를 만들어보겠습니다.

이전에 배운내용 처럼 

LinearLayout android:orientation="vertical" 옵션과 android:layout_weight 옵션을 사용 하여 화면을 굿헝합니다.

android_weight 는 비율로 생각하시면 됩니다.

4:1:1:1

<LinearLayout  세로 >

<LinearLayout 가로 > 가로 가로 가로 ... <LinearLayout >

<LinearLayout 가로 > 가로 가로 가로 ... <LinearLayout >

<LinearLayout 가로 > 가로 가로 가로 ... <LinearLayout >

...

</LinearLayout >


이런식으로 구성합니다.


res/layout/activity_calculator.xml


<!--?xml version="1.0" encoding="utf-8"?-->
<linearlayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="fill_parent" android:layout_height="fill_parent" android:orientation="vertical">
    <LinearLayout 
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="vertical">
    <LinearLayout 
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:layout_weight="3">
    <TextView
        android:id="@+id/text_result"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:gravity="right"
    android:textSize="30dip" >
    </TextView>
    </LinearLayout>
    <LinearLayout 
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:orientation="horizontal"
    android:layout_weight="1">
     <Button
        android:id="@+id/button_back"
        android:layout_width="wrap_content"
        android:layout_height="fill_parent"
        android:text="←" 
        android:layout_weight="1"/>
      <Button
        android:id="@+id/button_clear"
        android:layout_width="wrap_content"
        android:layout_height="fill_parent"
        android:text="C" 
        android:layout_weight="1"/>
       <Button
        android:id="@+id/button_equal"
        android:layout_width="wrap_content"
        android:layout_height="fill_parent"
        android:text="=" 
        android:layout_weight="1"/>
       <Button
        android:id="@+id/button_plus"
        android:layout_width="wrap_content"
        android:layout_height="fill_parent"
        android:text="+" 
        android:layout_weight="1"/> 
    </LinearLayout>
    <LinearLayout 
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:orientation="horizontal"
    android:layout_weight="1">
     <Button
        android:id="@+id/button_7"
        android:layout_width="wrap_content"
        android:layout_height="fill_parent"
        android:text="7"
        android:layout_weight="1" />
      <Button
        android:id="@+id/button_8"
        android:layout_width="wrap_content"
        android:layout_height="fill_parent"
        android:text="8" 
        android:layout_weight="1"/>
       <Button
        android:id="@+id/button_9"
        android:layout_width="wrap_content"
        android:layout_height="fill_parent"
        android:text="9"
        android:layout_weight="1" />
       <Button
        android:id="@+id/button_minus"
        android:layout_width="wrap_content"
        android:layout_height="fill_parent"
        android:text="-"
        android:layout_weight="1" />
    </LinearLayout>
    <LinearLayout 
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:orientation="horizontal"
    android:layout_weight="1">
     <Button
        android:id="@+id/button_4"
        android:layout_width="wrap_content"
        android:layout_height="fill_parent"
        android:text="4"
        android:layout_weight="1" />
      <Button
        android:id="@+id/button_5"
        android:layout_width="wrap_content"
        android:layout_height="fill_parent"
        android:text="5" 
        android:layout_weight="1"/>
       <Button
        android:id="@+id/button_6"
        android:layout_width="wrap_content"
        android:layout_height="fill_parent"
        android:text="6"
        android:layout_weight="1" />
       <Button
        android:id="@+id/button_multi"
        android:layout_width="wrap_content"
        android:layout_height="fill_parent"
        android:text="*"
        android:layout_weight="1" />
    </LinearLayout>
    <LinearLayout 
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:orientation="horizontal"
    android:layout_weight="1">
       <Button
        android:id="@+id/button_1"
        android:layout_width="wrap_content"
        android:layout_height="fill_parent"
        android:text="1" 
        android:layout_weight="1"/>
      <Button
        android:id="@+id/button_2"
        android:layout_width="wrap_content"
        android:layout_height="fill_parent"
        android:text="2" 
        android:layout_weight="1"/>
       <Button
        android:id="@+id/button_3"
        android:layout_width="wrap_content"
        android:layout_height="fill_parent"
        android:text="3" 
        android:layout_weight="1"/>
     
       <Button
        android:id="@+id/button_devide"
        android:layout_width="wrap_content"
        android:layout_height="fill_parent"
        android:text="/" 
        android:layout_weight="1"/>
    </LinearLayout>
</LinearLayout>


Layout_weight 를 사용할때 android:layout_height="wrap_content"를 사용해주세요

결과




public class CalculatorActivity extends Activity implements OnClickListener {
	private Button b1;
	private Button b2;
	private Button b3;
	private Button b4;
	private Button b5;
	private Button b6;
	private Button b7;
	private Button b8;
	private Button b9;
	private Button b_claer;
	private Button b_back;
	private Button b_devide;
	private Button b_plus;
	private Button b_minus;
	private Button b_multi;
	private Button b_equal;
	
	private TextView result;
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_calculator );	

		b1 = (Button) findViewById( R.id.button_1 );
		b1.setOnClickListener(this);
		b2 = (Button) findViewById( R.id.button_2 );
		b2.setOnClickListener(this);
		b3 = (Button) findViewById( R.id.button_3 );
		b3.setOnClickListener(this);
		b4 = (Button) findViewById( R.id.button_4 );
		b4.setOnClickListener(this);
		b5 = (Button) findViewById( R.id.button_5 );
		b5.setOnClickListener(this);
		b6 = (Button) findViewById( R.id.button_6 );
		b6.setOnClickListener(this);
		b7 = (Button) findViewById( R.id.button_7 );
		b7.setOnClickListener(this);
		b8 = (Button) findViewById( R.id.button_8 );
		b8.setOnClickListener(this);
		b9 = (Button) findViewById( R.id.button_9 );
		b9.setOnClickListener(this);
		b_claer = (Button) findViewById( R.id.button_clear );
		b_claer.setOnClickListener(this);
		b_back = (Button) findViewById( R.id.button_back );
		b_back.setOnClickListener(this);
		b_devide = (Button) findViewById( R.id.button_devide );
		b_devide.setOnClickListener(this);
		b_plus = (Button) findViewById( R.id.button_plus );
		b_plus.setOnClickListener(this);
		b_minus = (Button) findViewById( R.id.button_minus );
		b_minus.setOnClickListener(this);
		b_multi = (Button) findViewById( R.id.button_multi );
		b_multi.setOnClickListener(this);
		b_equal = (Button) findViewById( R.id.button_equal );
		b_equal.setOnClickListener(this);
		result = (TextView) findViewById( R.id.text_result );
	}

	@Override
	public void onClick(View v) {
		if( v.equals( b1 )){
			if( result.getText().length() == 1 && "0".equals(result.getText())){
				result.setText("1");
			}else {
				result.setText( result.getText()+"1");
			}
		}else if( v.equals( b2 )){
			if( result.getText().length() == 1 && "0".equals(result.getText())){
				result.setText("2");
			}else {
				result.setText( result.getText()+"2");
			}
		}else if( v.equals( b3 )){
			if( result.getText().length() == 1 && "0".equals(result.getText())){
				result.setText("3");
			}else {
				result.setText( result.getText()+"3");
			}
		}else if( v.equals( b4 )){
			if( result.getText().length() == 1 && "0".equals(result.getText())){
				result.setText("4");
			}else {
				result.setText( result.getText()+"4");
			}
		}else if( v.equals( b5 )){
			if( result.getText().length() == 1 && "0".equals(result.getText())){
				result.setText("5");
			}else {
				result.setText( result.getText()+"5");
			}
		}else if( v.equals( b6 )){
			if( result.getText().length() == 1 && "0".equals(result.getText())){
				result.setText("6");
			}else {
				result.setText( result.getText()+"6");
			}
		}else if( v.equals( b7 )){
			if( result.getText().length() == 1 && "0".equals(result.getText())){
				result.setText("7");
			}else {
				result.setText( result.getText()+"7");
			}
		}else if( v.equals( b8 )){
			if( result.getText().length() == 1 && "0".equals(result.getText())){
				result.setText("8");
			}else {
				result.setText( result.getText()+"8");
			}
		}else if( v.equals( b9 )){
			if( result.getText().length() == 1 && "0".equals(result.getText())){
				result.setText("9");
			}else {
				result.setText( result.getText()+"9");
			}
		}else if( v.equals( b_claer )){
			result.setText( "0");
		}else if( v.equals( b_back )){
			if( result.getText().length() != 0 ) {
				result.setText( result.getText().subSequence( 0 , result.getText().length()-1));
			}
		}else if( v.equals( b_devide )){
			result.setText( result.getText()+"/");
		}else if( v.equals( b_plus )){
			result.setText( result.getText()+"+");
		}else if( v.equals( b_minus )){
			result.setText( result.getText()+"-");
		}else if( v.equals( b_multi )){
			result.setText( result.getText()+"X");
		}else if( v.equals( b_equal )){
			result.setText( calc() );
		}
	}
	private String calc() {
		// 다음시간에 계속
		return "계산";
	}
}





ShinExample_04.zip

계산부분은 수정을 좀 해야하네요

Posted by App.SHIN
:

우선 레이아웃에 버튼을 추가합니다. 기존 TextView를 Button으로 바꾸었습니다.

res/layout/activity_main.xml

<linearlayout 
	xmlns:android="http://schemas.android.com/apk/res/android" 
	android:layout_width="match_parent" 
	android:layout_height="match_parent" 
	android:orientation="horizontal">
	<button 
		android:id="@+id/button1" 
		android:layout_width="fill_parent" 
		android:layout_height="wrap_content" 
		android:text="Next Activity">
	</button>
</linearlayout>

그러면 버튼이 뜹니다.
그리고 소스에서 OnClickListener를 추가합니다.


public class MainActivity extends Activity implements android.view.View.OnClickListener {
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
		Button b = (Button)findViewById(R.id.button1);
		b.setOnClickListener( this );
	}
	@Override
	public void onClick(View v) {
		Intent i = new Intent(this, NextActivity.class );
		startActivity(i);
	}
}


findViewById 를 이용하여 xml 파일에 설정된 id로 설정합니다.

그리고 setOnClickListener 로 현재 클래스를 설정합니다.

그리고 그렇게 하기위해서는 현재클래스에서 implements 를 이용하여 android.view.View.OnClickListener 를 구현해 주어야합니다.


android.view.View.OnClickListener 인터페이스는 onClick 메서드를 구현해야합니다.

그리고 해당 메서드에 다음 activity를 실행하는 코드를 추가합니다.

Intent i = new Intent(this, NextActivity.class );

intent의 첫번째 변수는 context이고 두번째는 실행될 class를 설정합니다.

그리고 startActivity 로 실행을합니다.


NextActivity.java내용입니다.

public class NextActivity extends Activity {
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main2 );	
	}
}



res/layout/activity_main2.xml

<linearlayout 
	xmlns:android="http://schemas.android.com/apk/res/android" 
	android:layout_width="match_parent" 
	android:layout_height="match_parent" 
	android:orientation="horizontal">
	<textview 
		android:id="@+id/textView1"
		android:layout_width="fill_parent" 
		android:layout_height="wrap_content" 
		android:text="Hello Activity2" 
		android:textappearance="?android:attr/textAppearanceLarge">
	</textview>
</linearlayout>


그리고 마지막으로 AndroidManifest.xml 에 신규 activity를 설정해줍니다.



    
    
        
            
                

                
            
        
            
        


<activity android:name="com.shin.shinexample.NextActivity"></activity> 를 추가합니다.

그리고 실행을 합니다~


    



ShinExample_03.zip


Posted by App.SHIN
:

안드로이드 강좌 따라하기 1 의 프로젝트를 다운받아 압축을 풉니다.

eclipse에서 File > Import 선택 > Existing Androi8d Code Into Workspace를 선택합니다.

Root Directory 에서 Browse.. 를 선택하여 압축을 푼 폴더를 선택합니다.

그러면 아래쪽 Projects에 아래와 같이 ShinExample이 나옵니다.

Finish를 선택합니다.

완성~


Posted by App.SHIN
:

1. 신택스 하이라이터를 다운받습니다. 

    http://alexgorbatchev.com/SyntaxHighlighter/  로 접속합니다.

    다운로드 메뉴 선택하여 다운을 받습니다.

    다운로드 

    다운로드한 파일을 압축을 풀어주세요.

2. 티스토리 설정에 업로드 합니다.


압축을 푼 내용중에 

scripts 폴더와 styles폴더의 내용을 


꾸미기 메뉴 -> HTML/CSS 편집 ->파일 업로드에서

확장자가 js와 css인 파일을 모두 업로드합니다.

























 

위 내용을 html/css설정에 </head> 위에 붙여넣습니다.


3. 본문에서 사용합니다.

글쓰기 부분에 상단 오른쪽에 HTML을 누룹니다.

그리고 

<pre class ="brush:사용할 언어">
 소스코드
 </pre>

부분을 입력하면 해당내용을 찾아보실수있습니다.



EX) 




Posted by App.SHIN
:

BLOG main image
by App.SHIN

공지사항

카테고리

분류 전체보기 (27)
안드로이드 (12)
추천앱 (0)
맛집 (0)
영화 (0)
핫이슈 (2)
서버 (2)
mac os 적응기 (8)
java (1)
mysql (1)
tomcat (1)

최근에 올라온 글

최근에 달린 댓글

최근에 받은 트랙백

글 보관함

달력

«   2025/04   »
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
Total :
Today : Yesterday :