sel.xml파일 생성및 res/raw/mp3파일 넣어주기




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

    <TextView
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:text="@string/hello" />

    <ImageButton
        android:id="@+id/imageButton1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:src="@drawable/sel" 
        android:layout_gravity="center"/>
    
    <Button
        android:id="@+id/button1"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="stop" />

</LinearLayout>
sel.xml
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android" >
    <!-- 눌러졌을때 보여질 이미지 선택 -->
    <item android:state_pressed="true"
          android:drawable="@drawable/red"/>
	
    <!-- 기본 상태에서 보여질 이미지 -->
	<item android:drawable="@drawable/yellow"/>
	    
</selector>




ServiceActivity.java
package com.gusfree.service;

import android.app.Activity;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.ImageButton;

public class ServiceActivity extends Activity {
    ImageButton imageButton;
    Button button;
    MediaPlayer mp;
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        
        imageButton=(ImageButton) findViewById(R.id.imageButton1);
        button = (Button)findViewById(R.id.button1);
       
        ClickListener listener = new ClickListener();
        imageButton.setOnClickListener(listener);
        button .setOnClickListener(listener) ;                

        mp = MediaPlayer.create(this, R.raw.riverside);
        
        
    }
    class ClickListener implements android.view.View.OnClickListener{
  
		@Override
		public void onClick(View v) {
			
			if(v==imageButton){//음악 시작
				imageButton.setEnabled(false);//못누르게
				mp.start();
			}else if(v==button) {//음악 종료
				imageButton.setEnabled(true);
				mp.pause();
			}
		}
    }
}



음악이 재생된다~~


문서가져오기 버튼/ 이미지가져오기 버튼

리스트뷰에 아이템을 클릭하면 다이얼로그로

파일 띄우기(이미지는 이미지가 나오게, text는 글이 나오게)


FileIOActivity.java


<?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
        android:layout_width="fill_parent"
        android:layout_height="wrap_content" >

        <Button
            android:id="@+id/button1"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="Button1" />

        <Button
            android:id="@+id/button2"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="Button2" />

        <Button
            android:id="@+id/button3"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="Button3" />
    </LinearLayout>

    <ListView
        android:id="@+id/listView1"
        android:layout_width="match_parent"
        android:layout_height="wrap_content" />

    <ScrollView
        android:id="@+id/scrollView1"
        android:layout_width="match_parent"
        android:layout_height="match_parent" >

        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="match_parent" >

            <TextView
                android:id="@+id/textView1"
                android:layout_width="fill_parent"
                android:layout_height="fill_parent"
                android:contentDescription="텍스트를 출력할 뷰" />
        </LinearLayout>
    </ScrollView>

</LinearLayout>
package com.gusfree.fileio;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;

import org.apache.http.util.ByteArrayBuffer;

import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ListView;
import android.widget.TextView;

public class FileIoActivity extends Activity implements OnClickListener{

	TextView tv;
	Button btn1,btn2,btn3;
	ByteArrayBuffer bab; 
	ListView lv;
	
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.main);

		//뷰찾고 리스너 세팅하기
		tv=(TextView) findViewById(R.id.textView1);
		lv=(ListView)findViewById(R.id.listView1);
		btn1=(Button) findViewById(R.id.button1);
		btn2=(Button) findViewById(R.id.button2);
		btn3=(Button) findViewById(R.id.button3);


		btn1.setOnClickListener(this);
		btn2.setOnClickListener(this);
		btn3.setOnClickListener(this);

	}
	int i=0;

	@Override
	public void onClick(View v) {
		switch(v.getId()){
		case R.id.button1: //text파일 내용읽어서 화면출력
			//Res폴더/raw/test.txt 가져오기
			InputStream is = 
			getResources().openRawResource(R.raw.text);

			int k=0;
			// read() 메서드는 한 바이트씩 읽어서 리턴,
			// 더이상 읽을 내용이 없으면 -1을 리턴합니다. 
			bab=new ByteArrayBuffer(50);			
			try{
				//while( ( k=is.read() )!= -1 ){
				for(  ;   ; ) {
					k=is.read();
					if(k==-1){
						break;
					}
					bab.append(k);					
				}         // 다 읽었다.
				//바이트배열버퍼 -> 스트링으로 변환시키기
				byte[] b = bab.toByteArray();
				String content = new String(b);
				tv.setText(content);
			}catch(Exception e){
			}
			break;
		case R.id.button2: //읽은 데이터를 파일로 저장하기
			i++;
			FileOutputStream  fos = null;
			try {
				fos = this.openFileOutput("test"+i+".txt",Activity.MODE_PRIVATE);
				fos.write(bab.toByteArray()); //save
				fos.flush() ;  // option 버퍼를 비워라
				fos.close();  // required 닫아라. 				

			} catch (Exception e) {	
				// window/ open perspective/ DDMS 추가
				// DDMS / Explorer / data/data/패키지/files/
			} finally{
				try{ if(fos!=null) fos.close();
				}
				catch(Exception e){
				}
			}
			break;
		case R.id.button3://저장된 파일 가져오기
			//  /data/data/패키지 이름/files/test1.txt
			
			File file=new File("data/data/com.gusfree.fileio/files/");
			//안에 들은 파일을 파일 배열로 return
			File[] fileList = file.listFiles();
			
			//파일 수만큼 파일 이름을 담을 수 있는 String 배열 생성
			String[] fileNames=new String[fileList.length];
			
			for(int i=0;i<fileNames.length;i++){
				//파일의 이름만 배열에 저장하자
				fileNames[i] =fileList[i].getName();
			}
			//간단한 어뎁터
			ArrayAdapter adapter = new ArrayAdapter(this, 
					android.R.layout.simple_list_item_1,fileNames);
			
			lv.setAdapter(adapter);
			break;
		}
	}
}


파일을 추가할수도있다




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

    <TextView
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:text="@string/hello" />

    <LinearLayout
        android:layout_width="fill_parent"
        android:layout_height="wrap_content" >

        <Button
            android:id="@+id/button1"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="Button" />

        <Button
            android:id="@+id/button2"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="Button" />

        <Button
            android:id="@+id/button3"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="Button" />
    </LinearLayout>

    <ScrollView
        android:id="@+id/scrollView1"
        android:layout_width="match_parent"
        android:layout_height="match_parent" >

        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="match_parent" >

            <TextView
                android:id="@+id/textView1"
                android:layout_width="fill_parent"
                android:layout_height="fill_parent"
                android:contentDescription="텍스트를 출력할 뷰" />
        </LinearLayout>
    </ScrollView>

</LinearLayout>
package com.gusfree.fileio;

import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;

import org.apache.http.util.ByteArrayBuffer;

import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;

public class FileIoActivity extends Activity implements OnClickListener{

	TextView tv;
	Button btn1,btn2,btn3;
	ByteArrayBuffer bab; 

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.main);

		//뷰찾고 리스너 세팅하기
		tv=(TextView) findViewById(R.id.textView1);
		btn1=(Button) findViewById(R.id.button1);
		btn2=(Button) findViewById(R.id.button2);
		btn3=(Button) findViewById(R.id.button3);


		btn1.setOnClickListener(this);
		btn2.setOnClickListener(this);
		btn3.setOnClickListener(this);

	}
	int i=0;

	@Override
	public void onClick(View v) {
		switch(v.getId()){
		case R.id.button1: //text파일 내용읽어서 화면출력
			//Res폴더/raw/test.txt 가져오기
			InputStream is = 
			getResources().openRawResource(R.raw.text);

			int k=0;
			// read() 메서드는 한 바이트씩 읽어서 리턴,
			// 더이상 읽을 내용이 없으면 -1을 리턴합니다. 
			bab=new ByteArrayBuffer(50);			
			try{
				//while( ( k=is.read() )!= -1 ){
				for(  ;   ; ) {
					k=is.read();
					if(k==-1){
						break;
					}
					bab.append(k);					
				}         // 다 읽었다.
				//바이트배열버퍼 -> 스트링으로 변환시키기
				byte[] b = bab.toByteArray();
				String content = new String(b);
				tv.setText(content);
			}catch(Exception e){
			}
			break;
		case R.id.button2: //읽은 데이터를 파일로 저장하기
			i++;
			FileOutputStream  fos = null;
			try {
				fos = this.openFileOutput("test"+i+".txt",Activity.MODE_PRIVATE);
				fos.write(bab.toByteArray()); //save
				fos.flush() ;  // option 버퍼를 비워라
				fos.close();  // required 닫아라. 				

			} catch (Exception e) {	
				// window/ open perspective/ DDMS 추가
				// DDMS / Explorer / data/data/패키지/files/
			} finally{
				try{ if(fos!=null) fos.close();
				}
				catch(Exception e){
				}
			}
			break;
		case R.id.button3:
			break;
		}
	}
}

가운데 버튼(R.id.button2)를 눌렀을때.......


DDMS((Dalvik Debug Monitor Service)를 보면  

// DDMS / Explorer / data/data/패키지/files/ 생성되는 것을 볼 수 있다.


'Android > 2012.04월 강좌' 카테고리의 다른 글

8일차 숙제  (0) 2012.05.07
8일차 FileIO 3 - 저장된 파일 가져오기  (0) 2012.05.07
8일차 FileIO - text파일 내용읽어서 화면출력  (2) 2012.05.07
8일차 Draw 3 TouchEvent  (0) 2012.05.07
8일차 Draw 2 TouchEvent  (0) 2012.05.07

Sidney Samson - Shake That Thing (Riverside) (feat. Twista )가사를 txt 파일로 우후후후


파일 저장시 utf-8로 저장을 해야 제대로 출력된다.




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

    <TextView
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:text="@string/hello" />

    <LinearLayout
        android:layout_width="fill_parent"
        android:layout_height="wrap_content" >

        <Button
            android:id="@+id/button2"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="Button" />

        <Button
            android:id="@+id/button3"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="Button" />

        <Button
            android:id="@+id/button1"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="Button" />

        <Button
            android:id="@+id/button4"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="Button" />
    </LinearLayout>

    <ScrollView
        android:id="@+id/scrollView1"
        android:layout_width="match_parent"
        android:layout_height="match_parent" >

        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="match_parent" >

            <TextView
                android:id="@+id/textView1"
                android:layout_width="fill_parent"
                android:layout_height="fill_parent"
                android:contentDescription="텍스트를 출력할 뷰" />
        </LinearLayout>
    </ScrollView>

</LinearLayout>
package com.gusfree.fileio;

import java.io.IOException;
import java.io.InputStream;

import org.apache.http.util.ByteArrayBuffer;

import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;

public class FileIoActivity extends Activity implements OnClickListener{

	TextView tv;
	Button btn1,btn2,btn3,btn4;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.main);

		//뷰찾고 리스너 세팅하기
		tv=(TextView) findViewById(R.id.textView1);
		btn1=(Button) findViewById(R.id.button1);
		btn2=(Button) findViewById(R.id.button2);
		btn3=(Button) findViewById(R.id.button3);
		btn4=(Button) findViewById(R.id.button4);

		btn1.setOnClickListener(this);
		btn2.setOnClickListener(this);
		btn3.setOnClickListener(this);
		btn4.setOnClickListener(this);
	}

	@Override
	public void onClick(View v) {
		switch(v.getId()){
		case R.id.button1://text파일 내용 읽어서 화면 출력
			// Res/raw/text.txt 가져오기
			InputStream is =getResources().openRawResource(R.raw.text);

			int k=0;
			//read()메서드는 한 바이트 씩 읽어서 리턴,
			//더이상 읽을 내용이 없으면 -1을 리턴합니다.
			ByteArrayBuffer bab = new ByteArrayBuffer(50);
			try {
				while((k=is.read())!=-1){
					bab.append(k);
				} //다 읽었다.
				
				//바이트 배열 -> 스트링의로 변환시키기
				byte[] b = bab.toByteArray();
				String content = new String(b);
				tv.setText(content);
			} catch (IOException e) {
				e.printStackTrace();
			}
			break;
		case R.id.button2:
			break;
		case R.id.button3:
			break;
		case R.id.button4:
			break;
		}
	}
}   


버튼을 누르면 res/raw/text.txt파일이 ScrallView에 구현된다.




가사의 출처


package com.gusfree.draw;

import java.io.InputStream;
import java.net.URL;
import java.util.Random;

import android.app.Activity;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Paint.Style;
import android.graphics.Rect;
import android.graphics.RectF;
import android.os.Bundle;
import android.util.Log;
import android.view.Display;
import android.view.MotionEvent;
import android.view.View;
import android.view.WindowManager;
import android.widget.Toast;

public class DrawActivity extends Activity {

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);

		setContentView(new MyView(this));

		WindowManager mWindowManager =

				(WindowManager)getSystemService(WINDOW_SERVICE);

		Display mDisplay = mWindowManager.getDefaultDisplay();

		Log.i("phoneInfo", "mDisplay.getWidth()>>> "+mDisplay.getWidth());

		Log.i("phoneInfo", "mDisplay.getHeight()>>> "+mDisplay.getHeight());

		// View  - TextView
	}

	class MyView extends View{

		public MyView(Context context) {
			super(context);			
		}

		@Override
		protected void onDraw(Canvas canvas) {			
			super.onDraw(canvas);
			Paint yellow=new Paint();
			yellow.setColor(Color.YELLOW);
			yellow.setAntiAlias(true);   
			canvas.drawCircle(160, 50, 20, yellow);

			yellow.setStyle(Style.STROKE);
			canvas.drawCircle(160+100, 50,20, yellow);

			yellow.setStrokeWidth(10);  //선 두껍게
			canvas.drawLine(160+20, 50+50, 
					160+100-20, 50+50, yellow);

			/*  mission : 동그라미 100개 random한 크기와 위치 */

			Random random = new Random();

			Paint rPaint=new Paint();
			//rPaint.setStyle(Style.STROKE);
			for(int i=0  ; i < 100  ; i++  ){
				int x = random.nextInt(320);  // 0~320까지 랜덤
				int y = random.nextInt(400);
				int r = random.nextInt(160);
				int red=random.nextInt(255);
				int green=random.nextInt(255);
				int blue=random.nextInt(255);
				rPaint.setColor(Color.argb(80, red, green, blue)); //0~255
				canvas.drawCircle(x, y, r, rPaint);
			}

			Paint bluePaint=new Paint();
			bluePaint.setColor(Color.BLUE);

			canvas.drawRect(100, 200,100+200, 200+50,bluePaint);

			RectF oval=new RectF(50, 50, 300, 100); //네모
			canvas.drawOval(oval, bluePaint);  //타원

			Paint white=new Paint();
			white.setColor(Color.WHITE);
			white.setTextSize(30);
			canvas.drawText("안녕하세요", 75, 75, white);

			canvas.drawArc(oval, 
					-360, 100, false, white);

			String addr="http://www.imaeil.com/news_img/2012/StarNews/20120504_170303000.jpg";
			try {
				URL url = new URL(addr); // String -> URL

				//단말기에서 WebServer로 데이터 요청 + Permission
				InputStream  is = url.openStream(); //요청 + 결과 받기

				//비트맵 공장에서 받은 데이터로 Bitmap 생성
				Bitmap bitmap=BitmapFactory.decodeStream(is);

				//비트맵을 지정된 위치에 그리기 
				//canvas.drawBitmap(bitmap, 10, 10, null);	

				//비트맵을 지정된 위치에 지정된 크기로 그리기
				Rect src=new Rect(0, 0,  //원래 크기 
						0+bitmap.getWidth(), 
						0+bitmap.getHeight());

				//원하는 위치와 크기
				RectF dst=new RectF(0, 200, 160, 360);
				canvas.drawBitmap(bitmap, null, dst, null);

			} catch (Exception e) {

			}
		}
	}
	//옵션메뉴 -> onOptionsItemSelected()
	
	//on: 콜백,자동,항상 ,TouchEvent
	@Override
	public boolean onTouchEvent(MotionEvent event) {
		
		setContentView(new MyView(this));
		
		Log.i("정보보기",event.getAction()+"");
		Log.i("onTouchEvent",event.getEventTime()+"");
		Log.w("onTouchEvent","X의 위치 :" +event.getRawX()+"");
		Log.w("onTouchEvent","Y의 위치 :" +event.getRawY()+"");
		Log.i("onTouchEvent",""+event.getDeviceId()+"");
		
		//터치 다운의 이벤트만 처리하기
		if(event.getAction()==MotionEvent.ACTION_DOWN){
			if(event.getRawX()>75&&event.getRawX()<75+100&&
					event.getRawY()>75&&event.getRawY()<75+100){
				Toast.makeText(DrawActivity.this, "안녕하세요", 0).show();
			}
		}
		return super.onTouchEvent(event);
	}
}

사진을 클릭시 그림이 다시 그려짐




package com.gusfree.draw;

import java.io.InputStream;
import java.net.URL;
import java.util.Random;

import android.app.Activity;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Paint.Style;
import android.graphics.Rect;
import android.graphics.RectF;
import android.os.Bundle;
import android.util.Log;
import android.view.Display;
import android.view.View;
import android.view.WindowManager;

public class DrawActivity extends Activity {
	/** Called when the activity is first created. */
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);

		setContentView(new MyView(this));

		WindowManager mWindowManager =

				(WindowManager)getSystemService(WINDOW_SERVICE);

		Display mDisplay = mWindowManager.getDefaultDisplay();

		Log.i("phoneInfo", "mDisplay.getWidth()>>> "+mDisplay.getWidth());

		Log.i("phoneInfo", "mDisplay.getHeight()>>> "+mDisplay.getHeight());

		// View  - TextView
	}

	class MyView extends View{

		public MyView(Context context) {
			super(context);			
		}

		@Override
		protected void onDraw(Canvas canvas) {			
			super.onDraw(canvas);
			Paint yellow=new Paint();
			yellow.setColor(Color.YELLOW);
			yellow.setAntiAlias(true);   
			canvas.drawCircle(160, 50, 20, yellow);

			yellow.setStyle(Style.STROKE);
			canvas.drawCircle(160+100, 50,20, yellow);

			yellow.setStrokeWidth(10);  //선 두껍게
			canvas.drawLine(160+20, 50+50, 
					160+100-20, 50+50, yellow);

			/*  mission : 동그라미 100개 random한 크기와 위치 */

			Random random = new Random();

			Paint rPaint=new Paint();
			//rPaint.setStyle(Style.STROKE);
			for(int i=0  ; i < 100  ; i++  ){
				int x = random.nextInt(320);  // 0~320까지 랜덤
				int y = random.nextInt(400);
				int r = random.nextInt(160);
				int red=random.nextInt(255);
				int green=random.nextInt(255);
				int blue=random.nextInt(255);
				rPaint.setColor(Color.argb(80, red, green, blue)); //0~255
				canvas.drawCircle(x, y, r, rPaint);
			}

			Paint bluePaint=new Paint();
			bluePaint.setColor(Color.BLUE);

			canvas.drawRect(100, 200,100+200, 200+50,bluePaint);

			RectF oval=new RectF(50, 50, 300, 100); //네모
			canvas.drawOval(oval, bluePaint);  //타원

			Paint white=new Paint();
			white.setColor(Color.WHITE);
			white.setTextSize(30);
			canvas.drawText("안녕하세요", 75, 75, white);

			canvas.drawArc(oval, 
					-360, 100, false, white);

			String addr="http://www.imaeil.com/news_img/2012/StarNews/20120504_165031000.jpg";
			try {
				URL url = new URL(addr); // String -> URL

				//단말기에서 WebServer로 데이터 요청 + Permission
				InputStream  is = url.openStream(); //요청 + 결과 받기

				//비트맵 공장에서 받은 데이터로 Bitmap 생성
				Bitmap bitmap=BitmapFactory.decodeStream(is);

				//비트맵을 지정된 위치에 그리기 
				//canvas.drawBitmap(bitmap, 10, 10, null);	

				//비트맵을 지정된 위치에 지정된 크기로 그리기
				Rect src=new Rect(0, 0,  //원래 크기 
						0+bitmap.getWidth(), 
						0+bitmap.getHeight());

				//원하는 위치와 크기
				RectF dst=new RectF(0, 200, 160, 360);
				canvas.drawBitmap(bitmap, null, dst, null);

			} catch (Exception e) {

			}
		}
	}
}




package com.gusfree.draw;

import android.app.Activity;
import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.os.Bundle;
import android.util.Log;
import android.view.Display;
import android.view.MotionEvent;
import android.view.View;
import android.view.WindowManager;

public class DrawActivity extends Activity {

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);

		setContentView(new MyView(this));

		WindowManager mWindowManager =

				(WindowManager)getSystemService(WINDOW_SERVICE);

		Display mDisplay = mWindowManager.getDefaultDisplay();

		Log.i("phoneInfo", "mDisplay.getWidth()>>> "+mDisplay.getWidth());

		Log.i("phoneInfo", "mDisplay.getHeight()>>> "+mDisplay.getHeight());

		// View  - TextView
	}

	class MyView extends View{

		public MyView(Context context) {
			super(context);			
		}

		@Override
		protected void onDraw(Canvas canvas) {			
			super.onDraw(canvas);

			Paint white=new Paint();
			white.setColor(Color.WHITE);
			white.setTextSize(30);
			canvas.drawText("안녕하세요", 75, 75, white);
		}



		//옵션메뉴 -> onOptionsItemSelected()

		//on: 콜백,자동,항상 ,TouchEvent
		@Override
		public boolean onTouchEvent(MotionEvent event) {



			Log.i("정보보기",event.getAction()+"");
			Log.i("onTouchEvent",event.getEventTime()+"");
			Log.w("onTouchEvent","X의 위치 :" +event.getRawX()+"");
			Log.w("onTouchEvent","Y의 위치 :" +event.getRawY()+"");
			Log.i("onTouchEvent",""+event.getDeviceId()+"");

			
			return super.onTouchEvent(event);
		}
	}
}


화면을 클릭한 부분의 좌표값이 나온다...로그캣으로...


package com.gusfree.draw;

import android.app.Activity;
import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.os.Bundle;
import android.util.Log;
import android.view.Display;
import android.view.MotionEvent;
import android.view.View;
import android.view.WindowManager;
import android.widget.Toast;

public class DrawActivity extends Activity {

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);

		setContentView(new MyView(this));

		WindowManager mWindowManager =

				(WindowManager)getSystemService(WINDOW_SERVICE);

		Display mDisplay = mWindowManager.getDefaultDisplay();

		Log.i("phoneInfo", "mDisplay.getWidth()>>> "+mDisplay.getWidth());

		Log.i("phoneInfo", "mDisplay.getHeight()>>> "+mDisplay.getHeight());

		// View  - TextView
	}

	class MyView extends View{

		public MyView(Context context) {
			super(context);			
		}

		@Override
		protected void onDraw(Canvas canvas) {			
			super.onDraw(canvas);

			Paint white=new Paint();
			white.setColor(Color.WHITE);
			white.setTextSize(30);
			canvas.drawText("안녕하세요", 75, 75, white);
		}



		//옵션메뉴 -> onOptionsItemSelected()

		//on: 콜백,자동,항상 ,TouchEvent
		@Override
		public boolean onTouchEvent(MotionEvent event) {



			Log.i("정보보기",event.getAction()+"");
			Log.i("onTouchEvent",event.getEventTime()+"");
			Log.w("onTouchEvent","X의 위치 :" +event.getRawX()+"");
			Log.w("onTouchEvent","Y의 위치 :" +event.getRawY()+"");
			Log.i("onTouchEvent",""+event.getDeviceId()+"");

			//터치 다운의 이벤트만 처리하기
			if(event.getAction()==MotionEvent.ACTION_DOWN){
				if(event.getRawX()>75&&event.getRawX()<75+100&&
						event.getRawY()>75&&event.getRawY()<75+100){
					Toast.makeText(DrawActivity.this, "안녕하세요", 0).show();
				}
			}
			return super.onTouchEvent(event);
		}
	}
}

안녕하세요 를 클릭시 다이얼로그가 뜬다~~~(폰테스트시 터치임)




'Android > 2012.04월 강좌' 카테고리의 다른 글

8일차 FileIO - text파일 내용읽어서 화면출력  (2) 2012.05.07
8일차 Draw 3 TouchEvent  (0) 2012.05.07
7일차 Draw  (0) 2012.05.04
7일차 Thread 2  (0) 2012.05.04
7일차 Thread  (0) 2012.05.04
package com.gusfree.draw;

import java.util.Random;

import android.app.Activity;
import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Paint.Style;
import android.os.Bundle;
import android.view.View;

public class DrawActivity extends Activity {

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);

		setContentView(new MyView(this));

		//View  - TextView
	}
	class MyView extends View{

		public MyView(Context context) {
			super(context);
		}
		@Override
		protected void onDraw(Canvas canvas) {
			super.onDraw(canvas);

			Paint yellow=new Paint();
			yellow.setColor(Color.YELLOW);
			yellow.setAntiAlias(true);
			canvas.drawCircle(160, 50, 20, yellow);

			yellow.setStyle(Style.STROKE);
			canvas.drawCircle(160+100, 50, 20, yellow);


			yellow.setStrokeWidth(10);//선 두껍게
			canvas.drawLine(160+20,50+50,160+100-20,50+50,yellow);

		}
	}
}




package com.gusfree.draw;

import java.util.Random;

import android.app.Activity;
import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Paint.Style;
import android.os.Bundle;
import android.view.View;

public class DrawActivity extends Activity {

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);

		setContentView(new MyView(this));

		//View  - TextView
	}
	class MyView extends View{

		public MyView(Context context) {
			super(context);
		}
		@Override
		protected void onDraw(Canvas canvas) {
			super.onDraw(canvas);

			Paint yellow=new Paint();
			yellow.setColor(Color.YELLOW);
			yellow.setAntiAlias(true);
			canvas.drawCircle(160, 50, 20, yellow);

			yellow.setStyle(Style.STROKE);
			canvas.drawCircle(160+100, 50, 20, yellow);


			yellow.setStrokeWidth(10);//선 두껍게
			canvas.drawLine(160+20,50+50,160+100-20,50+50,yellow);

			/* mission: 동그라미 100개 random한 크기와 위치*/			
			Random random = new Random();

			Paint rPaint=new Paint();
			for(int i=0;i<100;i++){
				int x =random.nextInt(320);//0~320까지 랜덤
				int y = random.nextInt(400);
				int r = random.nextInt(160);
				int red =random.nextInt();
				int green =random.nextInt();
				int blue =random.nextInt();
				rPaint.setColor(Color.rgb(red, green, blue));
				canvas.drawCircle(x, y, r, rPaint);

			}

		}
	}
}




package com.gusfree.draw;

import java.util.Random;

import android.app.Activity;
import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Paint.Style;
import android.graphics.RectF;
import android.os.Bundle;
import android.view.View;

public class DrawActivity extends Activity {

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);

		setContentView(new MyView(this));

		//View  - TextView
	}
	class MyView extends View{

		public MyView(Context context) {
			super(context);
		}
		@Override
		protected void onDraw(Canvas canvas) {
			super.onDraw(canvas);

			Paint bluePaint=new Paint();
			bluePaint.setColor(Color.BLUE);
			
			canvas.drawRect(100, 200,100+200,200+50,bluePaint);
			
			RectF oval=new RectF(50,50,300,100);
			canvas.drawOval(oval, bluePaint);
			
			
		}
	}
}  



package com.gusfree.draw;

import java.util.Random;

import android.app.Activity;
import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Paint.Style;
import android.graphics.RectF;
import android.os.Bundle;
import android.view.View;

public class DrawActivity extends Activity {

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);

		setContentView(new MyView(this));

		//View  - TextView
	}
	class MyView extends View{

		public MyView(Context context) {
			super(context);
		}
		@Override
		protected void onDraw(Canvas canvas) {
			super.onDraw(canvas);

			Paint white=new Paint();
			white.setColor(Color.WHITE);
			white.setTextSize(30);
			canvas.drawText("안녕하세요", 75, 75, white);
		}
	}
}



package com.gusfree.draw;

import java.util.Random;

import android.app.Activity;
import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Paint.Style;
import android.graphics.RectF;
import android.os.Bundle;
import android.view.View;

public class DrawActivity extends Activity {

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);

		setContentView(new MyView(this));

		//View  - TextView
	}
	class MyView extends View{

		public MyView(Context context) {
			super(context);
		}
		@Override
		protected void onDraw(Canvas canvas) {
			super.onDraw(canvas);

			Paint bluePaint=new Paint();
			bluePaint.setColor(Color.BLUE);
			
			canvas.drawRect(100, 200,100+200,200+50,bluePaint);
			
			RectF oval=new RectF(50,50,300,100);
			canvas.drawOval(oval, bluePaint);
			
			Paint white=new Paint();
			white.setColor(Color.WHITE);
			white.setTextSize(30);
			canvas.drawText("안녕하세요", 75, 75, white);
			canvas.drawArc(oval,-150, 100, false, white);
		}
	}
}  



package com.gusfree.draw;

import java.io.InputStream;

import java.net.URL;
import java.util.Random;

import android.app.Activity;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Paint.Style;
import android.graphics.RectF;
import android.os.Bundle;
import android.view.View;

public class DrawActivity extends Activity {

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);

		setContentView(new MyView(this));

		//View  - TextView
	}
	class MyView extends View{

		public MyView(Context context) {
			super(context);
		}
		@Override
		protected void onDraw(Canvas canvas) {
			super.onDraw(canvas);

			
			String addr="http://www.imaeil.com/news_img/2012/StarNews/20120504_170303000.jpg";
			try{
			URL url=new URL(addr);
			
			//단말기에서 WebServer로 데이터 요청	
			InputStream is=url.openStream();//요청+ 결과 받기
			
			//비트맵 공장에서 받은 데이터로 bitmap 생성
			Bitmap bitmap=BitmapFactory.decodeStream(is);
			
			BitmapFactory.decodeStream(is);
			
			
			canvas.drawBitmap(bitmap, 10, 10,null);
			}catch(Exception e){
				
			}
		}
	}
}  




'Android > 2012.04월 강좌' 카테고리의 다른 글

8일차 Draw 3 TouchEvent  (0) 2012.05.07
8일차 Draw 2 TouchEvent  (0) 2012.05.07
7일차 Thread 2  (0) 2012.05.04
7일차 Thread  (0) 2012.05.04
7일차 Notification  (0) 2012.05.04
<?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" >


    <TextView
        android:id="@+id/textView1"
        android:layout_width="wrap_content"
        android:layout_height="40dp"
        android:textSize="30dp"
        android:text="TextView" />

    <TextView
        android:id="@+id/textView2"
        android:layout_width="wrap_content"
        android:layout_height="40dp"
        android:textSize="30dp"
        android:text="TextView" />



    <ProgressBar
        android:id="@+id/progressBar1"
        style="?android:attr/progressBarStyleHorizontal"
        android:layout_width="match_parent"
        android:layout_height="wrap_content" />


    <Button
        android:id="@+id/button1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="시작" />

    <Button
        android:id="@+id/button2"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="정지" />

</LinearLayout>
package com.gusfree.thread;

import android.app.Activity;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;

public class ThreadActivity extends Activity {

	TextView tv1,tv2;//선언
	Button btn1, btn2;
	ProgressBar pb;
	MyHandler handler = new MyHandler();
	
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.main);

		//클래스 변수 초기화
		tv1=(TextView) this.findViewById(R.id.textView1);
		tv2=(TextView) this.findViewById(R.id.textView2);
		btn1=(Button) this.findViewById(R.id.button1);
		btn2=(Button) this.findViewById(R.id.button2);
		pb=(ProgressBar)this.findViewById(R.id.progressBar1);
		pb.setProgress(0);//진행정도 setting하기

		//버튼에 리스너 셋팅 callBack메서드 셋팅
		ButtonListener listener = new ButtonListener(); 
		btn1.setOnClickListener(listener);
		btn2.setOnClickListener(listener);
	}
	class ButtonListener implements OnClickListener{

		@Override 
		public void onClick(View v) {
			switch(v.getId()){
			case R.id.button1 :
				Plus plus1 = new Plus();//스레드 겍체 생성
				plus1.start();//run()안에 적어둔 일을 해라
				break;
			case R.id.button2 :
				Plus2 plus2 = new Plus2();
				plus2.start();// 스레드 생성+ 일시작
				tv1.setText(0+"");
				//Toast.makeText(this, "완료", 2000).show();
				break;
			}
		}
	}
	//innerClass 사용목적 :
	//OutterClass의 변수를 자율롭게 사용하기 위해
	class Plus extends Thread{


		@Override
		public void run() {//스레드가 할 일을 적어두는 곳
			android.util.Log.i("버튼 1클릭","버튼 1클릭");//import가 필요없다.
			/*1~100 숫자를 textview에 찍자*/
			for(int i=0;i<=100;i++){

				//서브스레드는 View에 접근할 수 없다.
				//tv1.setText(i+"");//Error

				//대안:핸들러에게 View에 접근하는일 시키자
				//send~~Message  : handleMessage호출
				Log.i("sendEmptyMessage","sendEmptyMessage"+i);
				handler.sendEmptyMessage(i);

				try{
					Thread.sleep(50);//0.05초 *100=5
				}catch(InterruptedException e){
					e.printStackTrace();
				}
			}
		}
	}
	//inner Class:서브스레드로부터 지시를 받아서 뷰 수정
	class MyHandler extends Handler{
		@Override
		public void handleMessage(Message msg) {
			Log.e("handleMessage","handleMessage");
			int number=msg.what;
			int number2=msg.what;
			
			if(number2==777){
				Toast.makeText(ThreadActivity.this,"in Handler 작업 끝",1).show();
			}else{
				tv1.setText(number+"핸들러가 찍습니다.");
			}
			super.handleMessage(msg);
		}
	}
	
	//ProgressBar 조금씩 올려주는 쓰레드
	class Plus2 extends Thread{
		
		@Override
		public void run() {
			//Toast.makeText(ThreadActivity.this, "in Thread", 0).show();//error
			for(int i=0;i<=100;i++){
				pb.setProgress(i);//된다!
				
				if(i==100){
					//핸들러에게 Toast를 시킨다
					handler.sendEmptyMessage(777);
					pb.setProgress(0);
				}
				try{
					Thread.sleep(50);
				}catch(InterruptedException e){
					e.printStackTrace();
				}
			}
		}

	}
} 





'Android > 2012.04월 강좌' 카테고리의 다른 글

8일차 Draw 2 TouchEvent  (0) 2012.05.07
7일차 Draw  (0) 2012.05.04
7일차 Thread  (0) 2012.05.04
7일차 Notification  (0) 2012.05.04
7일차 AnimationSet  (0) 2012.05.04
ANR

◎메인 스레드의 특징

5초 이상 작업을 하느라 화면이 멈추거나..

어플 종료(ANR - android not response)

CPU/ram Fast  -  Graphic은 자원을 많이 소모한다.

계산은 금방하고  - 화면 출력은 나중으로 미룸


◎서브스레드의 특징

계산은 잘한다 - Graphic 처리를 못함(android에서만)

        - View에 접근할 수 없다.


◎작업영역      ----......-----         뷰영역       

                          핸들러






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


    <TextView
        android:id="@+id/textView1"
        android:layout_width="wrap_content"
        android:layout_height="60dp"
        android:textSize="30dp"
        android:text="TextView" />

    <TextView
        android:id="@+id/textView2"
        android:layout_width="wrap_content"
        android:layout_height="60dp"
        android:textSize="30dp"
        android:text="TextView" />

    <Button
        android:id="@+id/button1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="시작" />

    <Button
        android:id="@+id/button2"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="정지" />

</LinearLayout>



package com.gusfree.thread;

import android.app.Activity;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;

public class ThreadActivity extends Activity {

	TextView tv1,tv2;//선언
	Button btn1, btn2;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.main);

		//클래스 변수 초기화
		tv1=(TextView) this.findViewById(R.id.textView1);
		tv2=(TextView) this.findViewById(R.id.textView2);
		btn1=(Button) this.findViewById(R.id.button1);
		btn2=(Button) this.findViewById(R.id.button2);

		//버튼에 리스너 셋팅 callBack메서드 셋팅
		ButtonListener listener = new ButtonListener(); 
		btn1.setOnClickListener(listener);
		btn2.setOnClickListener(listener);
	}
	class ButtonListener implements OnClickListener{

		@Override
		public void onClick(View v) {
			switch(v.getId()){
			case R.id.button1 :
				Plus plus1 = new Plus();//스레드 겍체 생성
				plus1.start();//run()안에 적어둔 일을 해라
				break;
			case R.id.button2 :
				Log.i("버튼 2클릭","버튼 2클릭");
				tv1.setText(0+"");
				break;
			}
		}
	}
	//innerClass 사용목적 :
	//OutterClass의 변수를 자율롭게 사용하기 위해
	class Plus extends Thread{

		//변수선언 및 초기화
		MyHandler handler = new MyHandler();

		@Override
		public void run() {//스레드가 할 일을 적어두는 곳
			android.util.Log.i("버튼 1클릭","버튼 1클릭");//import가 필요없다.
			/*1~100 숫자를 textview에 찍자*/
			for(int i=0;i<=100;i++){

				//서브스레드는 View에 접근할 수 없다.
				//tv1.setText(i+"");//Error

				//대안:핸들러에게 View에 접근하는일 시키자
				//send~~Message  : handleMessage호출
				Log.i("sendEmptyMessage","sendEmptyMessage"+i);
				handler.sendEmptyMessage(i);

				try{
					Thread.sleep(50);//0.05초 *100=5
				}catch(InterruptedException e){
					e.printStackTrace();
				}
			}
		}
	}
	//inner Class:서브스레드로부터 지시를 받아서 뷰 수정
	class MyHandler extends Handler{
		@Override
		public void handleMessage(Message msg) {
			Log.e("handleMessage","handleMessage");
			int number=msg.what;
			tv1.setText(number+"핸들러가 찍습니다.");
			
			super.handleMessage(msg);
		}
	}
} 



'Android > 2012.04월 강좌' 카테고리의 다른 글

7일차 Draw  (0) 2012.05.04
7일차 Thread 2  (0) 2012.05.04
7일차 Notification  (0) 2012.05.04
7일차 AnimationSet  (0) 2012.05.04
7일차 ScaleAnimation  (0) 2012.05.04

       Notification(하나하나의 알림), 

       NotificationManager,  (알림 관리자)

       Intent, (알림을 누르면 실행할 기능)

       PendingIntent  (인텐트의 wrapper)



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

    <Button
        android:id="@+id/button1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Button" />

</LinearLayout>


permission을 줘야 한다.

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.gusfree.notification"
    android:versionCode="1"
    android:versionName="1.0" >

    <uses-sdk android:minSdkVersion="8" />
    <uses-permission android:name="android.permission.CALL_PHONE"/>

    <application
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name" >
        <activity
            android:name=".NotificationActivity"
            android:label="@string/app_name" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>

</manifest>


package com.gusfree.notification;

import android.app.Activity;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.DialogInterface;
import android.content.Intent;

import android.net.Uri;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;

public class NotificationActivity extends Activity implements OnClickListener{

	
	@Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        
        findViewById(R.id.button1).setOnClickListener(this);
    }

	@Override
	public void onClick(View arg0){
		//1.알림 매니저 호출, android OS(platform)기능
		NotificationManager manager =
				(NotificationManager)getSystemService(NOTIFICATION_SERVICE);
		
		//2.단말기 위쪽에 뜰 알림 만들기
		Notification noti = 
				new Notification(R.drawable.red,"알림왔어요",System.currentTimeMillis());
		
		//5.알림 누르면 실행할 기능 만들기
		Intent intent= new Intent();
		intent.setAction(Intent.ACTION_CALL);//permission
		intent.setData(Uri.parse("tel:0123456789"));
		
		PendingIntent pending=PendingIntent.getActivity(this, 0, intent, 0);
		
		//3.위쪽에 뜬 알림을 드래그 했을 때 나올 한칸의 내용
		noti.setLatestEventInfo(this, 
				"contentTitle : 전화 요청", 
				"contentText : 0123456789", 
				pending);//알림 누르면 실행할 기능 PendingIntent
		
		//4.매니저에게 알림을 띄우도록 한다.
		manager.notify(0,noti);
	}
}




'Android > 2012.04월 강좌' 카테고리의 다른 글

7일차 Thread 2  (0) 2012.05.04
7일차 Thread  (0) 2012.05.04
7일차 AnimationSet  (0) 2012.05.04
7일차 ScaleAnimation  (0) 2012.05.04
7일차 RotateAnimation(setFillAfter,setRepeatCount)  (0) 2012.05.04

각 xml 세팅은 여기서 참조 하세요

http://gusfree.tistory.com/admin/entry/post/?id=803 

package com.gusfree.twinanimation;

import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.view.animation.AccelerateDecelerateInterpolator;
import android.view.animation.AlphaAnimation;
import android.view.animation.Animation;
import android.view.animation.AnimationSet;
import android.view.animation.RotateAnimation;
import android.view.animation.ScaleAnimation;
import android.view.animation.TranslateAnimation;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.Spinner;
import android.widget.Toast;

public class TwinAnimaionActivity extends Activity {
	Spinner spinner;
	ImageView imageView;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.main);

		spinner=(Spinner)findViewById(R.id.spinner1);
		imageView=(ImageView)findViewById(R.id.imageView1);

		ArrayAdapter adapter=
				ArrayAdapter.createFromResource(this,R.array.twin,
						android.R.layout.simple_spinner_item);

		adapter.setDropDownViewResource(android.R.layout.simple_dropdown_item_1line);
		spinner.setAdapter(adapter);

		spinner.setOnItemSelectedListener(new Lisetener());
	}
	class Lisetener implements OnItemSelectedListener{

		@Override
		public void onItemSelected(AdapterView<?> parent, View view, int position,
				long id) {
			Toast.makeText(TwinAnimaionActivity.this, position+"번째", 0).show();

			switch(position){
			//이동애니메이션 x시작점 x끝점 y시작점 y끝점
			//왼쪽 위(0,0) 오른쪽 아래 (320,460)
			case 0: TranslateAnimation ani0 = new TranslateAnimation(0, 320, 50, 50);

			ani0.setDuration(2000);
			imageView.startAnimation(ani0);
			spinner.startAnimation(ani0);

			break;

			case 1: TranslateAnimation ani1 = new TranslateAnimation(
					Animation.RELATIVE_TO_PARENT,0
					,Animation.RELATIVE_TO_PARENT,1
					,Animation.RELATIVE_TO_PARENT,0
					,Animation.RELATIVE_TO_PARENT,1);
			ani1.setDuration(2000);
			imageView.startAnimation(ani1);
			spinner.startAnimation(ani1);

			break;

			case 2: AlphaAnimation ani2 = new AlphaAnimation(1,0);//fade out
			ani2.setDuration(2000);
			imageView.startAnimation(ani2);
			spinner.startAnimation(ani2);

			break;
			                                       //~각도,->각도,x중심,y중심
			case 3: RotateAnimation ani3=new RotateAnimation(-360, 400,1,1);
			ani3.setDuration(2000);
			ani3.setFillAfter(true);//끝난 상태로 끝
			ani3.setRepeatCount(2);
			imageView.startAnimation(ani3);
			spinner.startAnimation(ani3);

			break;

			//크기 변경 애니메이션
			case 4: ScaleAnimation ani4= new ScaleAnimation(1, 5,1,5,5,5);
			ani4.setDuration(2000);
			imageView.startAnimation(ani4);
			spinner.startAnimation(ani4);
			
			case 5: AnimationSet set1= new AnimationSet(true);//가속도를 쓰겟다.
			RotateAnimation ani5=new RotateAnimation(-360, 400,1,1);//회전
			TranslateAnimation ani6 = new TranslateAnimation(0, 320, 50, 50);//이동
			AccelerateDecelerateInterpolator adi = new AccelerateDecelerateInterpolator();
			
			set1.addAnimation(ani5);
			set1.addAnimation(ani6);
			set1.setInterpolator(adi);
			set1.setDuration(2000);
			set1.setFillAfter(true);
			imageView.startAnimation(set1);
						
			}
		}
		@Override
		public void onNothingSelected(AdapterView<?> arg0) {

		}
	}
}    

빙글빙글돌아서 간다.


'Android > 2012.04월 강좌' 카테고리의 다른 글

7일차 Thread  (0) 2012.05.04
7일차 Notification  (0) 2012.05.04
7일차 ScaleAnimation  (0) 2012.05.04
7일차 RotateAnimation(setFillAfter,setRepeatCount)  (0) 2012.05.04
7일차 AlphaAnimation  (0) 2012.05.04

각 xml 세팅은 여기서 참조 하세요

http://gusfree.tistory.com/admin/entry/post/?id=803 

package com.gusfree.twinanimation;

import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.view.animation.AlphaAnimation;
import android.view.animation.Animation;
import android.view.animation.RotateAnimation;
import android.view.animation.ScaleAnimation;
import android.view.animation.TranslateAnimation;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.Spinner;
import android.widget.Toast;

public class TwinAnimaionActivity extends Activity {
	Spinner spinner;
	ImageView imageView;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.main);

		spinner=(Spinner)findViewById(R.id.spinner1);
		imageView=(ImageView)findViewById(R.id.imageView1);

		ArrayAdapter adapter=
				ArrayAdapter.createFromResource(this,R.array.twin,
						android.R.layout.simple_spinner_item);

		adapter.setDropDownViewResource(android.R.layout.simple_dropdown_item_1line);
		spinner.setAdapter(adapter);

		spinner.setOnItemSelectedListener(new Lisetener());
	}
	class Lisetener implements OnItemSelectedListener{

		@Override
		public void onItemSelected(AdapterView<?> parent, View view, int position,
				long id) {
			Toast.makeText(TwinAnimaionActivity.this, position+"번째", 0).show();

			switch(position){
			//이동애니메이션 x시작점 x끝점 y시작점 y끝점
			//왼쪽 위(0,0) 오른쪽 아래 (320,460)
			case 0: TranslateAnimation ani0 = new TranslateAnimation(0, 320, 50, 50);

			ani0.setDuration(2000);
			imageView.startAnimation(ani0);
			spinner.startAnimation(ani0);

			break;

			case 1: TranslateAnimation ani1 = new TranslateAnimation(
					Animation.RELATIVE_TO_PARENT,0
					,Animation.RELATIVE_TO_PARENT,1
					,Animation.RELATIVE_TO_PARENT,0
					,Animation.RELATIVE_TO_PARENT,1);
			ani1.setDuration(2000);
			imageView.startAnimation(ani1);
			spinner.startAnimation(ani1);

			break;

			case 2: AlphaAnimation ani2 = new AlphaAnimation(1,0);//fade out
			ani2.setDuration(2000);
			imageView.startAnimation(ani2);
			spinner.startAnimation(ani2);

			break;
			                                       //~각도,->각도,x중심,y중심
			case 3: RotateAnimation ani3=new RotateAnimation(-360, 400,1,1);
			ani3.setDuration(2000);
			imageView.startAnimation(ani3);
			spinner.startAnimation(ani3);

			break;

			//크기 변경 애니메이션
			case 4: ScaleAnimation ani4= new ScaleAnimation(1, 5,1,5,5,5);
			ani4.setDuration(2000);
			imageView.startAnimation(ani4);
			spinner.startAnimation(ani4);
			}
		}
		@Override
		public void onNothingSelected(AdapterView<?> arg0) {

		}
	}
}    

좌표값에 따라 이미지랑 스피너가 커짐


'Android > 2012.04월 강좌' 카테고리의 다른 글

7일차 Notification  (0) 2012.05.04
7일차 AnimationSet  (0) 2012.05.04
7일차 RotateAnimation(setFillAfter,setRepeatCount)  (0) 2012.05.04
7일차 AlphaAnimation  (0) 2012.05.04
7일차 TranslateAnimation  (0) 2012.05.04

각 xml 세팅은 여기서 참조 하세요

http://gusfree.tistory.com/admin/entry/post/?id=803 

package com.gusfree.twinanimation;

import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.view.animation.AlphaAnimation;
import android.view.animation.Animation;
import android.view.animation.RotateAnimation;
import android.view.animation.TranslateAnimation;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.Spinner;
import android.widget.Toast;

public class TwinAnimaionActivity extends Activity {
	Spinner spinner;
	ImageView imageView;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.main);

		spinner=(Spinner)findViewById(R.id.spinner1);
		imageView=(ImageView)findViewById(R.id.imageView1);

		ArrayAdapter adapter=
				ArrayAdapter.createFromResource(this,R.array.twin,
						android.R.layout.simple_spinner_item);

		adapter.setDropDownViewResource(android.R.layout.simple_dropdown_item_1line);
		spinner.setAdapter(adapter);

		spinner.setOnItemSelectedListener(new Lisetener());
	}
	class Lisetener implements OnItemSelectedListener{

		@Override
		public void onItemSelected(AdapterView<?> parent, View view, int position,
				long id) {
			Toast.makeText(TwinAnimaionActivity.this, position+"번째", 0).show();

			switch(position){
			//이동애니메이션 x시작점 x끝점 y시작점 y끝점
			//왼쪽 위(0,0) 오른쪽 아래 (320,460)
			case 0: TranslateAnimation ani0 = new TranslateAnimation(0, 320, 50, 50);

			ani0.setDuration(2000);
			imageView.startAnimation(ani0);
			spinner.startAnimation(ani0);
			
			break;

			case 1: TranslateAnimation ani1 = new TranslateAnimation(
					Animation.RELATIVE_TO_PARENT,0
					,Animation.RELATIVE_TO_PARENT,1
					,Animation.RELATIVE_TO_PARENT,0
					,Animation.RELATIVE_TO_PARENT,1);
			ani1.setDuration(2000);
			imageView.startAnimation(ani1);
			spinner.startAnimation(ani1);
			
			break;
			
			case 2: AlphaAnimation ani2 = new AlphaAnimation(1,0);//fade out
			ani2.setDuration(2000);
			imageView.startAnimation(ani2);
			spinner.startAnimation(ani2);
			
			break;
			                                        //~각도,->각도,x중심,y중심
			case 3: RotateAnimation ani3=new RotateAnimation(-360, 400,1,1);
			ani3.setDuration(2000);
			imageView.startAnimation(ani3);
			spinner.startAnimation(ani3);
			
			break;
			}
		}
		@Override
		public void onNothingSelected(AdapterView<?> arg0) {

		}
	}
}    

농구로 치면 내가 잘하는 피벗 플레이다..ㅎㅎㅎㅎㅎ





case 3: RotateAnimation ani3=new RotateAnimation(-360, 400,1,1);
			ani3.setDuration(2000);
			ani3.setFillAfter(true);//끝난 상태로 끝
			ani3.setRepeatCount(2)
			imageView.startAnimation(ani3);
			spinner.startAnimation(ani3);


setFillAfter 사용하는경우 마지막에 이렇게 끝난다.

setRepeatCount 반복횟수


'Android > 2012.04월 강좌' 카테고리의 다른 글

7일차 AnimationSet  (0) 2012.05.04
7일차 ScaleAnimation  (0) 2012.05.04
7일차 AlphaAnimation  (0) 2012.05.04
7일차 TranslateAnimation  (0) 2012.05.04
7일차 복습  (0) 2012.05.04

각 xml 세팅은 여기서 참조 하세요

http://gusfree.tistory.com/admin/entry/post/?id=803 

package com.gusfree.twinanimation;

import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.view.animation.AlphaAnimation;
import android.view.animation.Animation;
import android.view.animation.TranslateAnimation;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.Spinner;
import android.widget.Toast;

public class TwinAnimaionActivity extends Activity {
	Spinner spinner;
	ImageView imageView;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.main);

		spinner=(Spinner)findViewById(R.id.spinner1);
		imageView=(ImageView)findViewById(R.id.imageView1);

		ArrayAdapter adapter=
				ArrayAdapter.createFromResource(this,R.array.twin,
						android.R.layout.simple_spinner_item);

		adapter.setDropDownViewResource(android.R.layout.simple_dropdown_item_1line);
		spinner.setAdapter(adapter);

		spinner.setOnItemSelectedListener(new Lisetener());
	}
	class Lisetener implements OnItemSelectedListener{

		@Override
		public void onItemSelected(AdapterView<?> parent, View view, int position,
				long id) {
			Toast.makeText(TwinAnimaionActivity.this, position+"번째", 0).show();

			switch(position){
			//이동애니메이션 x시작점 x끝점 y시작점 y끝점
			//왼쪽 위(0,0) 오른쪽 아래 (320,460)
			case 0: TranslateAnimation ani0 = new TranslateAnimation(0, 320, 50, 50);

			ani0.setDuration(2000);
			imageView.startAnimation(ani0);
			spinner.startAnimation(ani0);
			
			break;

			case 1: TranslateAnimation ani1 = new TranslateAnimation(
					Animation.RELATIVE_TO_PARENT,1
					,Animation.RELATIVE_TO_PARENT,1
					,Animation.RELATIVE_TO_PARENT,0
					,Animation.RELATIVE_TO_PARENT,1);
			ani1.setDuration(100);
			imageView.startAnimation(ani1);
			spinner.startAnimation(ani1);
			
			break;
			
			case 2: AlphaAnimation ani2=
					new AlphaAnimation(1,0);//fade out
			ani2.setDuration(2000);
			imageView.startAnimation(ani2);
			spinner.startAnimation(ani2);
			
			break;
			}
		}
		@Override
		public void onNothingSelected(AdapterView<?> arg0) {

		}
	}
}    

이미지뷰와 스피너가 점점 살아진다(Fade Out)


'Android > 2012.04월 강좌' 카테고리의 다른 글

7일차 ScaleAnimation  (0) 2012.05.04
7일차 RotateAnimation(setFillAfter,setRepeatCount)  (0) 2012.05.04
7일차 TranslateAnimation  (0) 2012.05.04
7일차 복습  (0) 2012.05.04
6일차 TwinAnimaion  (0) 2012.05.03

+ Recent posts