Let's Re⇒move -31ページ目

Androidの授業 14 [ 簡単なアプリの作成 ③ ]

【EasyMaruBatu】


・RelativeLayoutを使用してみる。
 相対的な配置のできるレイアウト

○×ゲーム


main.xmlの作成
-----------------------------------
<?xml version="1.0" encoding="utf-8"?>
<FrameLayout xmlns:android="
http://schemas.android.com/apk/res/android "
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingRight="10dp"
android:paddingLeft="10dp"
android:background="#123456" >

<RelativeLayout
android:layout_width="300dp"
android:layout_height="300dp"
android:background="@drawable/background" >

<!-- id/centerをレイヤーの中央に配置 -->
<ImageButton
android:id="@+id/center"
android:layout_width="75dp"
android:layout_height="75dp"
android:layout_centerInParent="true"
android:layout_margin="20dp"
android:background="@drawable/none" />

<!-- id/topをid/centerの上(above)に配置 -->
<ImageButton
android:id="@+id/top"
android:layout_width="75dp"
android:layout_height="75dp"
android:layout_above="@+id/center"
android:layout_alignLeft="@+id/center"
android:background="@drawable/none" />

<!-- id/bottomをid/centerの下(below)に配置 -->
<ImageButton
android:id="@+id/bottom"
android:layout_width="75dp"
android:layout_height="75dp"
android:layout_below="@+id/center"
android:layout_alignLeft="@+id/center"
android:background="@drawable/none" />

<!-- id/leftをid/centerの左に配置 -->
<ImageButton
android:id="@+id/left"
android:layout_width="75dp"
android:layout_height="75dp"
android:layout_toLeftOf="@+id/center"
android:layout_alignTop="@+id/center"
android:background="@drawable/none" />

<!-- id/left_topを左をid/left、上をid/topに合わせて配置 -->
<ImageButton
android:id="@+id/left_top"
android:layout_width="75dp"
android:layout_height="75dp"
android:layout_alignLeft="@+id/left"
android:layout_alignTop="@+id/top"
android:background="@drawable/none" />

<!-- id/left_bottomを左をid/left、下をid/bottomに合わせて配置 -->
<ImageButton
android:id="@+id/left_bottom"
android:layout_width="75dp"
android:layout_height="75dp"
android:layout_alignLeft="@+id/left"
android:layout_alignBottom="@+id/bottom"
android:background="@drawable/none" />

<!-- id/rightをid/centerの右に配置 -->
<ImageButton
android:id="@+id/right"
android:layout_width="75dp"
android:layout_height="75dp"
android:layout_toRightOf="@+id/center"
android:layout_alignTop="@+id/center"
android:background="@drawable/none" />

<!-- id/right_topを右をid/right、上をid/topに合わせて配置 -->
<ImageButton
android:id="@+id/right_top"
android:layout_width="75dp"
android:layout_height="75dp"
android:layout_alignRight="@+id/right"
android:layout_alignTop="@+id/top"
android:background="@drawable/none" />

<!-- id/right_bottomを右をid/right、下をid/bottomに合わせて配置する -->
<ImageButton
android:id="@+id/right_bottom"
android:layout_width="75dp"
android:layout_height="75dp"
android:layout_alignRight="@+id/right"
android:layout_alignBottom="@+id/bottom"
android:background="@drawable/none" />


</RelativeLayout>

</FrameLayout>
--------------------------------------------------------------


・クラス[flag]の作成
-----------------------------
package test.easymarubatu;

public enum Flag {
Black,White,None
}
---------------------------
・クラス[GameOverException]の作成
※ extends Exceptionとすると警告が発生
    →生成シリアル・バージョンIDの追加を選ぶ
→serialVersionUID= --一意の数値----- が追加される。
-----------------------------------------
package test.easymarubatu;

public class GameOverException extends Exception {
private static final long
serialVersionUID = 1718809908471038178L;

public GameOverException() {
super();
}

public GameOverException(String detailMessage, Throwable throwable) {
super(detailMessage, throwable);
}

public GameOverException(String detailMessage) {
super(detailMessage);
}

public GameOverException(Throwable throwable) {
super(throwable);
}

}
-----------------------------


MainActivity.javaの編集

-----------------------------
package test.easymarubatu;

import java.util.ArrayList;
import java.util.List;

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

public class MainActivity extends Activity {

/** イメージボタンをリストで保持する*/
private ImageButton[] rectButtons =new ImageButton[9];

/** ゲームが完了しているかどうか */
private boolean isGameOver = false;

/** 現在のターン(先手か後手か)*/
private Flag currentTurn = Flag.Black;

/** 先手のチェック用リスト */
private List<Integer> blackTerritories =
new ArrayList<Integer>();

/** 後手のチェック用リスト */
private List<Integer> whiteTerritories =
new ArrayList<Integer>();

/** ボタンを押した時の処理 */
private View.OnClickListener onClickListener=new View.OnClickListener(){
@Override
public void onClick(View v){
}
};

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

//イメージボタンインスタンスの取得をし、配列に設定
rectButtons[0] =
(ImageButton) findViewById(R.id.left_top);
rectButtons[1] =
(ImageButton) findViewById(R.id.left);
rectButtons[2] =
(ImageButton) findViewById(R.id.left_bottom);
rectButtons[3] =
(ImageButton) findViewById(R.id.top);
rectButtons[4] =
(ImageButton) findViewById(R.id.center);
rectButtons[5] =
(ImageButton) findViewById(R.id.bottom);
rectButtons[6] =
(ImageButton) findViewById(R.id.right_top);
rectButtons[7] =
(ImageButton) findViewById(R.id.right);
rectButtons[8] =
(ImageButton) findViewById(R.id.right_bottom);

//リスナーの設定
for (ImageButton ib : rectButtons) {
ib.setOnClickListener(onClickListener);
}
}

}
--------------------------------------------------
ここまでで終了。
続きは次回。

Androidの授業 13 [ viewを動かしてみる ]

【 MoveView 】


・Viewを動かしてみる
 長押しで移動開始


・座標の計算


①layout→value フォルダに新規Android.xmlファイル"color.xml"を作成

----------------------------------
color.xml
----------------------------------
<?xml version="1.0" encoding="utf-8"?>
<resources>
<color name="view_color">#000000</color>
<color name="layout_color">#ffffff</color>
<color name="view_color_select">#66000000</color>
</resources>
----------------------------------


②main.xmlを編集
----------------------------------
<?xml version="1.0" encoding="utf-8"?>
<FrameLayout xmlns:android="
http://schemas.android.com/apk/res/android "
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="@color/layout_color" >

<View
android:id="@+id/view1"
android:layout_width="100dip"
android:layout_height="100dip"
android:layout_gravity="center"
android:background="@color/view_color" />
</FrameLayout>
-----------------------------------
*FrameLayoutでないとできないわけではないので注意

MainActivity.javaの編集

・継承する。
・メソッドの仮作成
・リスナーの作成
・長押し時のメソッドを埋める
・タッチ時のメソッドを埋める
---------------------------------------------
package test.moveview2;


import android.app.Activity;

import android.os.Bundle;
import android.view.MotionEvent;

import android.view.View;
import android.view.View.OnLongClickListener;

import android.view.View.OnTouchListener;

import android.view.animation.AlphaAnimation;

import android.view.animation.AnimationSet;

import android.view.animation.ScaleAnimation;


public class FrameMoveActivity
extends Activity
implements OnTouchListener, OnLongClickListener{


/** 移動対象のView */

private View move_view;


/** 長押しチェック用フラグ */

private boolean longClickFlg = false;


/** Viewの左辺座標:X軸 */

int currentX;


/** Viewの上辺座標:Y軸 */

int currentY;


/** 画面タッチ位置の座標:X軸 */

int offsetX;


/** 画面タッチ位置の座標:Y軸 */

int offsetY;



@Override

public void onCreate(Bundle savedInstanceState) {

super.onCreate(savedInstanceState);
setContentView(R.layout.main);


// 移動対象Viewのインスタンス取得

move_view = findViewById(R.id.view1);


// リスナーの設定

move_view.setOnLongClickListener(this);

move_view.setOnTouchListener(this);



move_view.bringToFront();

}


/**
* タッチ時
*/

@Override

public boolean onTouch(View v, MotionEvent event) {

int x = (int) event.getRawX();

int y = (int) event.getRawY();

switch(event.getAction()){

case MotionEvent.ACTION_DOWN:

currentX = v.getLeft();

currentY = v.getTop();

offsetX = x;

offsetY = y;

break;

case MotionEvent.ACTION_MOVE:

//長押しがされたかチェック

if(longClickFlg) {

int diffX = offsetX - x;

int diffY = offsetY - y;


currentX = currentX - diffX;

currentY = currentY - diffY;

v.layout(currentX,

currentY,

currentX + v.getWidth(),

currentY + v.getHeight()

);

offsetX = x

offsetY = y;
}

break;

case MotionEvent.ACTION_CANCEL:

case MotionEvent.ACTION_UP:

if(longClickFlg) {

v.setBackgroundResource

(R.color.view_color);

}

longClickFlg = false;

break;

}

return false;
}


/**
* 長押し時
*/

@Override

public boolean onLongClick(View v) {

// 長押しチェックをtrueに変更

longClickFlg = true;


// 状態の変化を視覚的に分かるように色の変更

v.setBackgroundResource
(R.color.view_color_select);


//アニメーションの設定

AnimationSet animationSet =

new AnimationSet(false);

// スケール

ScaleAnimation scale =

new ScaleAnimation(1,1.2f,1,1.2f, 0, 0);

scale.setDuration(300);

animationSet.addAnimation(scale);

// 透過

AlphaAnimation alpha =

new AlphaAnimation(0, 1);

alpha.setDuration(300);

animationSet.addAnimation(alpha);


v.startAnimation(animationSet);

return false;

}

}

Androidの授業 12 [ 簡単なアプリ②-2 ]

【 色当てゲーム 続き 】


昨日の続き。

順番にコメントアウトを埋めながら作って行きます。


※見たことのないメソッド等が出てきた時は必ず
 公式リファレンスに一度は目を通しておくこと。


授業の説明順
---------------------------------------
//押されたボタンによって色を判定する
switch(v.getId()) {
case R.id.btn_red: // 赤を押した時
selectColor = Color.RED;
break;
case R.id.btn_blue: // 青を押した時
selectColor = Color.BLUE;
break;
case R.id.btn_green: // 緑を押した時
selectColor = Color.GREEN;
break;
case R.id.btn_yellow: // 黄を押した時
selectColor = Color.YELLOW;
break;
case R.id.btn_gray: // 灰を押した時
selectColor = Color.GRAY;
break;
case R.id.btn_black: // 黒を押した時
selectColor = Color.BLACK;
break;
}
--------------------------------


/** 正解のIDを保持用 **/
private static int correct;
--------------------------------
if(selectColor == correct) {
tv.setText("正解です");

// 正解音

// 正解数のカウントを更新

} else {
// 不正解音
}
// 次の問題を表示
nextQuestion();
}
--------------------------------


/**
* 次の問題を表示
*/
private void nextQuestion() {
TextView tv = (TextView)findViewById(R.id.tv_question);

//文字の設定
tv.setText(getQuestionStr());
//色の設定
tv.setTextColor(getQuestionColor());

// 問題数・正解数を更新
}
----------------------------------

/** 問題文字用配列 **/
private static final String[] quesStringArray =
{"赤","青","緑","黄","灰","黒"};


/** 問題色用配列 **/
private static final int[] quesColorArray =
{Color.RED, Color.BLUE, Color.GREEN,
Color.YELLOW, Color.GRAY, Color.BLACK};


/** 乱数発生用 **/
private static final Random rnd = new Random();
-----------------------------------


/**
* 赤・青・緑・黄・灰・黒の中からランダムな文字列を取得
*/
private String getQuestionStr() {
int index = rnd.nextInt(quesStringArray.length);

// 正解を保持しておく
correct = quesColorArray[index];

return quesStringArray[index];
}

/**
* 赤・青・緑・黄・灰・黒の中からランダムな色を取得
*/
private int getQuestionColor() {
int index = rnd.nextInt(quesColorArray.length);

// 正解の色と重複している場合別の色を設定する
//(要素数が奇数の時対応できない)
if(correct == quesColorArray[index]) {
index = quesColorArray.length -1 -index;

}
/* ほかの方法①
* if(correct == quesColorArray[index]) {
* index = index - 1;
* if(index < 0) {
* index = quesColorArray.length -1;
* }
* }
* ほかの方法②
* int index = 0;
* while(true) {
* index = rnd.nextInt(quesColorArray.length);
* if(correct != quesColorArray[index2] {
* break;
* }
* }
*/

return quesColorArray[index];
}

-------------------------------------------
残りのフィールドを埋める
-------------------------------------------
/** 問題数 **/
private int questionCount;

/** 正解数 **/
private int correctCount;

/** 効果音 **/
private SoundPool pool;

/** 効果音ID(正解) **/
private int correctSound;

/** 効果音ID(不正解) **/
private int missSound;
-------------------------------------------

*音を鳴らすクラス
MedialayerとSoundPoolの違い
・同時に音を鳴らせるかどうか(1インスタンスで)
・音の長さ
-------------------------------------------

/**
* 効果音の設定
*/
private void setSound() {
pool = new SoundPool(10,AudioManager.STREAM_MUSIC,0);
correctSound = pool.load(this, R.raw.correct,1);
missSound = pool.load(this, R.raw.miss,1);
}

-------------------------------------------
*loadメソッドは別スレッドで動く為、長い音のファイル等は鳴らない可能性がある。

*SoundPool(10,AudioManager.STREAM_MUSIC,0)の引数について
10 →同時に鳴らせる最大数


-------------------------------------------
onCreate内の音の部分を埋める
-------------------------------------------

// 正解音
pool.play(correctSound, 1.0f, 1.0f, 1, 0, 1.0f);

// 不正解音
pool.play(missSound, 1.0f, 1.0f, 1, 0, 1.0f);
-------------------------------------------
/**
* 画面が表示されなくなった時
*/
@Override
protected void onPause() {
super.onPause();
// SoundPoolの開放
pool.release();
}
------------------------------------------

残った部分(本来カスタマイズ部分)
問題数と正解数の表示
------------------------------------------
// 正解数のカウントを更新
correctCount++;
-----------------------------------
// 問題数・正解数を更新
questionCount++;
updateQuestionView();
-----------------------------------
/**
* 問題数・正解数の表示内容を更新
*/
private void updateQuestionView() {
// 問題数の更新
TextView tvQuestionCount =
(TextView)findViewById(R.id.tv_question_count);
tvQuestionCount.setText(String.valueOf(questionCount));

// 正解数の更新
TextView tvCorrectCount =
(TextView)findViewById(R.id.tv_question_correct);
tvCorrectCount.setText(String.valueOf(correctCount));

// 問題数のカウントを更新
}
------------------------------------

これで完成です。実行してみて下さい。