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
:

안녕하세요 안드로이드 강좌를 시작하게된 Shin 입니다.


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">
<textview 
	android:id="@+id/calculator" 
	android:layout_width="fill_parent" 
	android:layout_height="wrap_content" 
	android:text="@string/hello_world" 
	android:textappearance="?android:attr/textAppearanceLarge">
</textview>
</linearlayout>


자바파일 내용은~

public class MainActivity extends Activity {

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


이렇게만 수정해도 hello world 가 찍히네요

LinearLayout 은  좌에서 우 , 위에서 아래로 추가되는 틀이 만들어집니다.

기본으로 위에서 아래로 됩니다.

만약 명시적으로 지정하시고 싶으시면   android:orientation 속성으로 지정하시면 됩니다.  값은 vertical , horizontal 이 있습니다.

horizontal 은 좌에서 우로 vertical 은 위에서 아래로입니다.


그럼 실행해볼까요?

우선 휴대폰을 셋팅합니다~

설정 > 개발자옵션 > 개발자옵션 ON > USB디버깅 켜기 > USB디버깅 허용 확인




설정이 끝났다면 실행을 합니다. 

프로젝트를 선택하고 Run As > Android Application 을 선택합니다.

위에설정을 하고  usb연결을 해두었다면 아래와 같이 단말이 보입니다.



실행결과 화면 ~


예제 프로젝트입니다. 

ShinExample.zip



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 :