1. Compass


package org.android.soldesk.mycompass_011;

import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.hardware.Sensor;
import android.hardware.SensorEvent;
import android.hardware.SensorEventListener;
import android.hardware.SensorManager;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;

public class MyCompass_011Activity extends AppCompatActivity implements SensorEventListener{
private SensorManager mSensorManager;
private Sensor morientation;
CompassView compass;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_my_compass_011);
compass=new CompassView(MyCompass_011Activity.this);
setContentView(compass);
mSensorManager= (SensorManager) getSystemService(SENSOR_SERVICE);
morientation=mSensorManager.getDefaultSensor(Sensor.TYPE_ORIENTATION);
}
protected void onResume(){
super.onResume();
mSensorManager.registerListener(this,morientation,SensorManager.SENSOR_DELAY_UI);
}
protected void onPause(){
super.onPause();
mSensorManager.unregisterListener(this);
}

@Override
public void onSensorChanged(SensorEvent event) {
if(event.sensor.getType()==Sensor.TYPE_ORIENTATION){
compass.setAzimuth(event.values[0]);//x
compass.setPitch(event.values[1]);//y
compass.setRoll(-event.values[2]);//z
compass.invalidate();
}
}

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

}
}
class CompassView extends View{
private float azimuth;
private float pitch;
private float roll;

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

public void setAzimuth(float azimuth) {
this.azimuth = azimuth;
}

public void setPitch(float pitch) {
this.pitch = pitch;
}

public void setRoll(float roll) {
this.roll = roll;
}

@Override
protected void onDraw(Canvas canvas) {
Paint paint = new Paint(Paint.ANTI_ALIAS_FLAG);
paint.setColor(Color.GREEN);
canvas.save();
canvas.rotate(-azimuth, 250, 250);
canvas.drawCircle(250, 250, 200, paint);
paint.setColor(Color.BLACK);
paint.setTextSize(50);
canvas.drawText("N", 250, 80, paint);
canvas.drawText("S", 250, 430, paint);
canvas.drawRect(240, 80, 260, 400, paint);
canvas.restore();
}
}

<java>




2. ProgressBar


<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context="org.android.soldesk.progress_01.Progress_01Activity">

<Button
android:id="@+id/btnBar"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:onClick="show"
android:text="Bar 형식의 Progress Dialog"/>

</LinearLayout>

<xml>


package org.android.soldesk.progress_01;

import android.app.Dialog;
import android.app.DialogFragment;
import android.app.ProgressDialog;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.ProgressBar;

public class Progress_01Activity extends AppCompatActivity {
static ProgressDialog dialog;
int pValue;//다이얼로그 설정값
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_progress_01);
}
public void show(View v){
final MyDialogFragment frag= MyDialogFragment.newInstance();
frag.show(getFragmentManager(),"TAG");
//작업 쓰레드 시작
Thread t= new Thread(new Runnable() {
@Override
public void run() {
while (pValue<100){
pValue++;
try{
dialog.setProgress(pValue);
Thread.sleep(100);
}catch (Exception e){
e.printStackTrace();
}
}
frag.dismiss();
pValue=0;
}
});
t.start();
}

public static class MyDialogFragment extends DialogFragment{
public static MyDialogFragment newInstance(){
return new MyDialogFragment();
}

@Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
dialog=new ProgressDialog(getActivity());
dialog.setTitle("Title");
dialog.setMessage("Message");
dialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
return dialog;
}
}
}

<java>




3. DomPasing


<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="org.android.soldesk.dompasing_01.DomPasing_01Activity">

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

</LinearLayout>

<xml>


package org.android.soldesk.dompasing_01;

import android.provider.DocumentsContract;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.ArrayAdapter;
import android.widget.ListView;

import org.w3c.dom.Document;
import org.w3c.dom.NodeList;

import java.io.InputStream;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;

public class DomPasing_01Activity extends AppCompatActivity {

ListView listView;

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

listView = (ListView) findViewById(R.id.listView1);

//파싱 데이터를 배열에 저장
String[]data = xmlPasing();

ArrayAdapter<String> adapter = new ArrayAdapter<String>(
getApplicationContext(),
android.R.layout.simple_list_item_1,
data);

listView.setAdapter(adapter);

}//end onCreate

//DOM 파싱
public String[] xmlPasing(){
String[] data = null;

try {
//res/raw 폴더에서XML 읽기
InputStream is = getResources().openRawResource(R.raw.student);

DocumentBuilderFactory factory =
DocumentBuilderFactory.newInstance();
DocumentBuilder builder = factory.newDocumentBuilder();
Document doc = builder.parse(is);

//name 값얻기
NodeList studentList = doc.getElementsByTagName("student");
NodeList nameList = doc.getElementsByTagName("name");
NodeList ageList = doc.getElementsByTagName("age");
NodeList emailList = doc.getElementsByTagName("email");
NodeList addressList = doc.getElementsByTagName("address");

data = new String[studentList.getLength()];

for (int i = 0; i < studentList.getLength(); i++){
String name = nameList.item(i).getFirstChild().getNodeValue();
String age = ageList.item(i).getFirstChild().getNodeValue();
String email = emailList.item(i).getFirstChild().getNodeValue();
String address = addressList.item(i).getFirstChild().getNodeValue();
data[i] = name + " " + age + " " +email+" "+ address;
}
}catch (Exception e){e.printStackTrace();}
return data;
}

/* DOM(Document Object Model) 은 XML 문서를 파싱하기위해
XML 문서 내용을 모두 메모리에 올려 놓고 처리하는 방식이다.
메모리에 올릴때 XML 문서내의 태그들을 모두 트리 구조로 변경시키고
파싱 작업을 한다.
또한 각 태그와 속성 등에 해당하는 객체(Object) 를 사용하여
파싱 작업을 구현하기 때문에 DOM 이라고 부른다.



Parsing(파싱) : 구문 분석 : 그것을 이루고 있는 구성 성분을 분석하여
그들 사이의 위계관계를 분석하여 문장의 구조 파악
*/
}

<java>


<person>
<student>
<name>홍길동</name>
<age>20</age>
<email>a@naver.com</email>
<address>서울시</address>
</student>
<student>
<name>수선화</name>
<age>23</age>
<email>b@naver.com</email>
<address>제주도</address>
</student>
<student>
<name>이순신</name>
<age>45</age>
<email>c@naver.com</email>
<address>전라도</address>
</student>
<student>
<name>백합</name>
<age>36</age>
<email>d@naver.com</email>
<address>경상도</address>
</student>
</person>

<student.xml>




4. XmlPullParser


<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context="org.android.soldesk.xmlpullparser.XmlPullParserActivity">

<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="회원 아이디 출력"
android:textSize="20pt"
/>

<Button
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="@+id/load"
android:text="Load~~~"
/>

<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="@+id/result"
android:textSize="16pt"
android:text=""
/>

</LinearLayout>

<xml>


package org.android.soldesk.xmlpullparser;



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

import org.xmlpull.v1.XmlPullParser;
import org.xmlpull.v1.XmlPullParserFactory;

import java.io.InputStream;
import java.io.InputStreamReader;

public class XmlPullParserActivity extends AppCompatActivity implements View.OnClickListener{

TextView result;
View load;

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

result = (TextView) findViewById(R.id.result);
load = (Button) findViewById(R.id.load);

load.setOnClickListener(this);
}

@Override
public void onClick(View v){

StringBuffer sb = new StringBuffer();
try{
XmlPullParser xp = getResources().getXml(R.xml.member);

while (xp.getEventType() != XmlPullParser.END_DOCUMENT){

if (xp.getEventType() == XmlPullParser.START_TAG){
/*
XmlPullParser 을 이용한 파싱 작업은 getEventType() 메소드로
구현한다. 이 메소드가 리턴하는 상수 값을 비교하면서 파싱 작업이 이루어지는데

정의 된 상수는 아래와 같다

XmlPullParser.START_DOCUMENT : xml 문서의 시작을 의미한다
XmlPullParser.END_DOCUMENT : xml 문서의 끝을 의미한다
XmlPullParser.START_TAG : xml 문서내의 시작 태그를 의미한다
XmlPullParser.END_TAG : xml 문서내의 end 태그를 의미한다
XmlPullParser.TEXT : getText() 메소드를 이용하여 얻는 문자 데이타를 의미한다
*/

if (xp.getName().equals("member2")){
sb.append(xp.getAttributeValue(0)+"\n");
}
}
xp.next();
}
result.setText(sb.toString());
}catch (Exception e){
e.printStackTrace();
Toast.makeText(XmlPullParserActivity.this,"로드 실패",
Toast.LENGTH_SHORT).show();
}
}
}

<java>


<memberlist>
<member2 id="kor">
<name>홍길동</name>
<age>34</age>
<weight>78</weight>
<height>183</height>
</member2>

<member2 id="seo">
<name>나훈아</name>
<age>64</age>
<weight>88</weight>
<height>176</height>
</member2>

<member2 id="kin">
<name>남진</name>
<age>67</age>
<weight>78</weight>
<height>183</height>
</member2>

<member2 id="kor">
<name>홍길동</name>
<age>34</age>
<weight>78</weight>
<height>183</height>
</member2>

</memberlist>

<member.xml>




5. Json_01


package org.android.soldesk.json_01;

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;

import org.json.JSONArray;
import org.json.JSONException;

public class Json_01Activity extends AppCompatActivity {

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

//JSON 배열 데이터
String data ="[ 1, 2, 3, 4, 5, 6, 7, 8, 9, 10]";

/*
JSON(Javascript Object Notation)
: 데이타를 구조화하는 이유는 여러 시스템과의
데이타 교환을 위해서 입니다.
데이타 베이스, 웹페이지 등 다른 시스템 과의
데이타 교환 송,수신할때 데이타가 구조화된
문장으로 이루어져 있다면 어디에서부터 어디까지가 속성이고 값인지
명확하게 알 수 있어 효율적인 데이타 교환이 가능합니다.

웹 프로그램의 개발의 자료 포맷은 xml 을 많이 사용하지만
파싱 작업이 번거롭고 많은 시간이 소모되는 단점이 있습니다.
즉 xml 은 tag 의 반복으로 이루어져있기 때문에 작성이 쉽고
가독성이 좋다는 장점도 있지만 tag 항목의 반복적 사용으로
문서의 양이 늘어 난다는 단점이 있습니다.
이러한 것을 개선하기 위해 문자열로 간단하게 표현하는 포맷인
JSON 이 탄생하게 됩니다.
JSON 은 최소한의 정보를 담고 있어 XML 보다 가벼우나 함축적이기
때문에 가독성이 떨어질 수 있는 단점이 있습니다.
*/

try {
JSONArray array = new JSONArray(data);

for (int i = 0; i < array.length();i++){
int n = array.getInt(i);
Log.i("MyTag","JSON 파싱 값: "+ n);
}
} catch (JSONException e1) {
e1.printStackTrace();
}
}
}

<java>




6. Json_02


package org.android.soldesk.json_02;

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;

import org.json.JSONArray;
import org.json.JSONObject;

public class Json_02Activity extends AppCompatActivity {

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

// JSON 객체배열
String str =
"[ {\"이름\":\"유관순\",\"전화\":\"010-3333-4444\",\"나이\":20,\"이메일\":a@naver.com}," +
"{\"이름\":\"홍길동\",\"전화\":\"010-6666-8888\",\"나이\":30,\"이메일\":b@naver.com},"+
"{\"이름\":\"이순신\",\"전화\":\"010-7777-5555\",\"나이\":40,\"이메일\":c@naver.com}]";

// 배열 형식 : [값1, 값2, 값3]
// 객체 형식 : [이름:값1, 이름:값2,]

try{

JSONArray array = new JSONArray(str);

for (int i = 0; i < array.length();i++){

JSONObject obj = array.getJSONObject(i);
String name = obj.getString("이름");
String tel = obj.getString("전화");
int age = obj.getInt("나이");
String email = obj.getString("이메일");
Log.i("MyTag", name + " "+ tel +" "+ age +" "+email);
}
}catch (Exception e){e.printStackTrace();}
}
}

<java>




7. WebView


package org.android.soldesk.webview_01;

import android.app.TabActivity;
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.TabHost;

public class WebView_01Activity extends TabActivity {

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

TabHost host = getTabHost();

host.addTab(host.newTabSpec("one")
.setIndicator("BrowerA")
.setContent(new Intent(this,BrowerA.class)));

host.addTab(host.newTabSpec("two")
.setIndicator("BrowerB")
.setContent(new Intent(this,BrowerB.class)));

host.addTab(host.newTabSpec("c")
.setIndicator("BrowerC")
.setContent(new Intent(this,BrowerC.class)));
}
}

<java>


package org.android.soldesk.webview_01;

import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.webkit.WebView;
import android.webkit.WebViewClient;

public class BrowerA extends AppCompatActivity{

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

WebView browser = new WebView(this);
setContentView(browser);

browser.loadUrl("http://www.daum.net");
browser.setWebViewClient(new WebViewClient());
// WebView 상에서 구동
}
}

<BrowerA.java>


package org.android.soldesk.webview_01;

import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.webkit.WebView;
import android.webkit.WebViewClient;

public class BrowerB extends AppCompatActivity{

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

WebView browser = new WebView(this);
setContentView(browser);

browser.loadUrl("http://www.google.com");
browser.setWebViewClient(new WebViewClient());
}
}

<BrowerB.java>


package org.android.soldesk.webview_01;

import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.webkit.WebView;
import android.webkit.WebViewClient;

public class BrowerC extends AppCompatActivity{

protected void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
// setContentView(R.layout.main);

WebView browser = new WebView(this);
setContentView(browser);

browser.loadUrl("http://www.naver.com");
browser.setWebViewClient(new WebViewClient());
}
}

<BrowerC.java>


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

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

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

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

</manifest>

<AndroidManifest.xml>




8. Game


<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context="org.android.soldesk.game_011.Game_011Activity">


<LinearLayout
android:layout_height="wrap_content"
android:layout_width="fill_parent"
android:orientation="horizontal"
android:layout_weight="1">

<TextView
android:text="@string/strYou"
android:textSize="18sp"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center_vertical"
android:layout_marginLeft="10dip"/>
<TextView
android:id="@+id/scrYou"
android:text="0"
android:textSize="18sp"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="1"
android:layout_gravity="center_vertical"/>
<TextView
android:text="@string/strPhone"
android:textSize="18sp"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center_vertical"/>
<TextView
android:id="@+id/scrPhone"
android:text="0"
android:textSize="18sp"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="1"
android:layout_gravity="center_vertical"/>
<TextView
android:textSize="18sp"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:gravity="right"
android:layout_weight="0.5"
android:layout_gravity="center_vertical" android:text="@string/strTot"/>
<TextView
android:id="@+id/scrTot"
android:text="0"
android:textSize="18sp"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center_vertical"
android:layout_marginRight="10dip"/>
</LinearLayout>

<TextView
android:id="@+id/txtTitle"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_weight="1"
android:gravity="top|center"
android:text="@string/strTitle"
android:textColor="#FF0000"
android:textSize="20pt" />

<LinearLayout
android:layout_height="wrap_content"
android:orientation="horizontal"
android:layout_gravity="center"
android:layout_width="wrap_content"
android:layout_weight="1">

<Button
android:id="@+id/Button01"
android:text="@string/strButton1"
android:layout_height="wrap_content"
android:layout_width="80dip"
android:layout_gravity="center"
android:tag="0"/>
<Button
android:id="@+id/Button02"
android:text="@string/strButton2"
android:layout_height="wrap_content"
android:layout_width="80dip"
android:layout_gravity="center"
android:layout_marginLeft="15dip"
android:layout_marginRight="15dip"
android:tag="1"/>
<Button
android:id="@+id/Button03"
android:text="@string/strButton3"
android:layout_height="wrap_content"
android:layout_width="80dip"
android:layout_gravity="right|center"
android:tag="2"/>
</LinearLayout>

<LinearLayout
android:layout_height="wrap_content"
android:layout_width="wrap_content"
android:layout_gravity="center"
android:layout_weight="5">

<ImageView
android:id="@+id/ImageView01"
android:src="@drawable/img_1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:layout_marginRight="40dip"/>
<ImageView
android:id="@+id/ImageView02"
android:src="@drawable/img_3"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:layout_marginLeft="40dip"/>
</LinearLayout>

<TextView
android:id="@+id/txtResult"
android:text="@string/strResult1"
android:layout_height="wrap_content"
android:layout_weight="1"
android:layout_width="wrap_content"
android:layout_gravity="center"
android:textColor="#ff000000"
android:textSize="20pt"/>

</LinearLayout>

<xml>


<resources>
<string name="app_name">가위 바위 보</string>
<string name="strYou">홍길동~~:</string>
<string name="strButton5">게임 끝</string>
<string name="strButton4">시작</string>
<string name="strButton3">보</string>
<string name="strResult0">비겼습니다!</string>
<string name="strTitle">가위 바위 보</string>
<string name="strResult1">당신이 이겼습니다!</string>
<string name="strButton1">가위</string>
<string name="strResult2">당신이 졌습니다!</string>
<string name="strButton2">바위</string>
<string name="strPhone">헨드폰!!! :</string>
<string name="strTot">게임 수 :</string>

</resources>

<string.xml>


package org.android.soldesk.game_011;

import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Matrix;
import android.os.Handler;
import android.os.Message;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;

import java.util.Random;

public class Game_011Activity extends AppCompatActivity {


private int arrImage[] = { 0, 0, 0 }; // 가위 바위보 이미지
private int arrScore[] = { 0, 0, 0 }; // 화면 상단 점수
private int arrSResult[] = { 0, 0, 0 }; // 승패 표시용 (비김, 이김, 짐)
private int arrButton[] = { 0, 0, 0, 0 }; // 버튼 Text

private int TitleColor = 0xFF00FF00; // 제목줄 글자 색깔 - ARGB
private int counter = 0; // 제목줄 글자 색깔 지연 카운터
private boolean isRun = true; // 타이머가 가동중인가?

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_game_011);
findViewById(R.id.Button01).setOnClickListener(myClick);
findViewById(R.id.Button02).setOnClickListener(myClick);
findViewById(R.id.Button03).setOnClickListener(myClick);

InitGame(); // 게임 초기화
mHandler.sendEmptyMessageDelayed(0, 300);
}

// ----------------------------------------
// 게임 초기화 - 변수 설정 등
// ----------------------------------------
public void InitGame() {
arrImage[0] = R.drawable.img_1; // 가위
arrImage[1] = R.drawable.img_2; // 바위
arrImage[2] = R.drawable.img_3; // 보

arrSResult[0] = R.string.strResult0; // 비김
arrSResult[1] = R.string.strResult1; // 이김
arrSResult[2] = R.string.strResult2; // 짐

arrButton[0] = R.string.strButton2; // '바위'
arrButton[1] = R.string.strButton3; // '보'
arrButton[2] = R.string.strButton4; // '시작'
arrButton[3] = R.string.strButton5; // '게임 끝'

((TextView) findViewById(R.id.txtResult)).setText(""); // 맨 아래 승부 표시 지움
}

// ----------------------------------
// OnClickListener
// ----------------------------------
View.OnClickListener myClick = new View.OnClickListener() {
public void onClick(View v) {
int you = Integer.parseInt(v.getTag().toString()); // 버튼의 Tag 읽기
if (isRun == true) { // 게임이 진행중이면
int phone = new Random().nextInt(3); // 난수 발생하고
isRun = false; // 타이머 중지
SetButtons(false); // [시작]/[게임끝] 보이도록
PanJung(you, phone);
} else { // [시작]/[게임끝] 중하나를 눌렀을 때
if (you == 1) { // [시작] 버튼이면
SetButtons(true); // 버튼을 [가위/바위/보] 상태로 바꾸고
isRun = true; // 타이머를 기동하도록 하고
mHandler.sendEmptyMessageDelayed(0, 0); // 타이머 호출
} else { // [게임끝] 버튼이면
finish(); // 프로그램 종료
return; // 이건 없어도 될듯...
} // if
} // if
} // onClick
}; // myClick

// ----------------------------------------
// 버튼 감추기 / 보이기
// ----------------------------------------
void SetButtons(boolean flag) {
if (flag == false) { // [가위] 버튼 감추기
((Button) findViewById(R.id.Button01))
.setVisibility(View.INVISIBLE);
((Button) findViewById(R.id.Button02)).setText(arrButton[2]);
((Button) findViewById(R.id.Button03)).setText(arrButton[3]);

// 프로그램 제목 다시 표시 (혹시 안보이는 상태일 수도 있으니까)
TitleColor = 0xFFFF0000;
((TextView) findViewById(R.id.txtTitle)).setTextColor(TitleColor);

} else { // [가위] 버튼 보이기
((Button) findViewById(R.id.Button01)).setVisibility(View.VISIBLE);
((Button) findViewById(R.id.Button02)).setText(arrButton[0]);
((Button) findViewById(R.id.Button03)).setText(arrButton[1]);
((TextView) findViewById(R.id.txtResult)).setText(""); // 맨 아래 승부 표시
// 지움
}
} // SetButtons

// ----------------------------------------
// 승부 판정
// ----------------------------------------
void PanJung(int you, int phone) {
int result;

if (you == phone)
result = 0; // 비김
else if (you - phone == 1 || you - phone == -2)
result = 1; // 이김
else
result = 2; // 짐

if (result != 0)
arrScore[result]++; // 승패 기록
arrScore[0]++; // 전체 게임 수

Display(you, phone, result); // 점수 및 이미지 표시
} // PanJung

// ----------------------------------------
// 점수, 가위 바위 보 이미지 표시
// ----------------------------------------
void Display(int you, int phone, int result) {
ImageView imgYou = (ImageView) findViewById(R.id.ImageView01);
ImageView imgPhone = (ImageView) findViewById(R.id.ImageView02);

// 가위바위보 이미지 표시
// imgYou.setImageResource(arrImage[you]);
MakeReverse(arrImage[you]);
imgPhone.setImageResource(arrImage[phone]);

// 승패 표시
((TextView) findViewById(R.id.txtResult)).setText(arrSResult[result]);

// 상단 점수 표시
((TextView) findViewById(R.id.scrYou)).setText(" " + arrScore[1]);
((TextView) findViewById(R.id.scrPhone)).setText(" " + arrScore[2]); // phone
((TextView) findViewById(R.id.scrTot)).setText(" " + arrScore[0]); // total
} // Display

// ----------------------------------------
// 이미지 뒤집기
// ----------------------------------------
void MakeReverse(int id) {
Bitmap bitmap, reverse;
Matrix matrix = new Matrix();
matrix.postScale(-1, 1); // 수평으로 뒤집기

// 원래의 이미지 읽고 폭과 높이를 구한다
bitmap = BitmapFactory.decodeResource(getResources(), id);
int w = bitmap.getWidth();
int h = bitmap.getHeight();

// 가로로 뒤집힌 이미지를 만든다
reverse = Bitmap.createBitmap(bitmap, 0, 0, w, h, matrix, false);

// ImageView01에 뒤집힌 이미지 할당
((ImageView) findViewById(R.id.ImageView01)).setImageBitmap(reverse);
} // MakeReverse

// ----------------------------------------
// 제목 깜박거림, 이미지 랜덤 표시
// ----------------------------------------
public void DrawBlink() {
Random rnd = new Random();
int n1 = counter % 3;
int n2 = rnd.nextInt(3);

counter++;
if (counter % 2 == 1) { // 글자는 이미지 절반의 주기로 깜박거림
TitleColor = 0xFFFFFF00 - TitleColor;
((TextView) findViewById(R.id.txtTitle)).setTextColor(TitleColor);
}
MakeReverse(arrImage[n1]); // 이미지 뒤집기
((ImageView) findViewById(R.id.ImageView02))
.setImageResource(arrImage[n2]);
} // DrawBlink

// ----------------------------------------
// 타이머 핸들러
// ----------------------------------------
Handler mHandler = new Handler() {
public void handleMessage(Message msg) {
if (isRun == false)
return;
DrawBlink();
mHandler.sendEmptyMessageDelayed(0, 300);
}
}; // Handler
}

<java>


+ Recent posts