【Androidアプリ作成】広告表示にはViewGroup#addViewを使え

ゲームで広告を表示したいけど、広告のために複雑なプログラムを書くのはちょっとめんどい。

そんなときは、xmlで広告とゲームを同時に表示するレイアウトを作っておいて、
広告用のViewを常時表示しつつ、ゲーム用のViewを必要に応じて入れ替えると
ゲーム部分のプログラムと広告用のプログラムを分離できるので、保守性が高まります。
使うのは以下の2つです。
・LayoutInflater#inflate

// レイアウトリソースIDを指定してViewを生成する
・ViewGroup#addView

// ViewGroupにViewをaddする

■レイアウト(app.xml)
<?xml version="1.0" encoding="utf-8"?>
<FrameLayout

xmlns:android="http://schemas.android.com/apk/res/android"

android:id="@+id/vgApp"

android:layout_width="fill_parent"

android:layout_height="fill_parent"
>

<!–
ゲーム –>

<View

android:layout_width="wrap_content"

android:layout_height="wrap_content" />

<!– 広告 –>

<広告会社提供のView

android:id="@+id/vwAd"

android:layout_width="wrap_content"

android:layout_height="wrap_content"

android:scrollbars="none"

android:layout_gravity="bottom"

android:layout_marginBottom="0px" />
</FrameLayout>

■Activity
以下のようなメソッドを追加
void setGameView(int layoutResID)
{

// ビューを変更する

View vw = getLayoutInflater().inflate(layoutResID, null);

ViewGroup vgApp = (ViewGroup)findViewById(R.id.vgApp);

vgApp.removeViewAt(0); // 前回のビューを潰して

vgApp.addView(vw,0); // 新しいビューを設定
}

■入れ替えるView(title.xml)
<?xml version="1.0" encoding="utf-8"?>
<FrameLayout

xmlns:android="http://schemas.android.com/apk/res/android"

android:layout_width="fill_parent"

android:layout_height="fill_parent" >

<ImageView

android:layout_width="fill_parent"

android:layout_height="fill_parent"

android:src="@drawable/title_bg"
/>
</FrameLayout>

・・・ここまで来れば、あとは必要なタイミングでsetGameView(R.layout.title)とか呼ぶだけ!楽チン。
Activityのとこに書いてある「vgApp.addView(vw,0);」がミソです。

2011.6.11

NECO

コメントを残す

メールアドレスが公開されることはありません。

CAPTCHA

*