
<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	>

<channel>
	<title>サイト構築日記</title>
	<atom:link href="http://memories.zal.jp/WP/feed" rel="self" type="application/rss+xml" />
	<link>http://memories.zal.jp/WP</link>
	<description>wordpress HSP3 開発環境構築</description>
	<lastBuildDate>Sun, 22 Jan 2012 15:44:14 +0000</lastBuildDate>
	<language>ja</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=3.3</generator>
		<item>
		<title>スピナー について</title>
		<link>http://memories.zal.jp/WP/blog/20120123_2218.html</link>
		<comments>http://memories.zal.jp/WP/blog/20120123_2218.html#comments</comments>
		<pubDate>Sun, 22 Jan 2012 15:42:13 +0000</pubDate>
		<dc:creator>admin</dc:creator>
				<category><![CDATA[Android]]></category>
		<category><![CDATA[Hello_Views]]></category>

		<guid isPermaLink="false">http://memories.zal.jp/WP/?p=2218</guid>
		<description><![CDATA[Android developers による「Hello Views」チュートリアルで紹介されているウィジットには次のようなものがあります。 Date Picker Time Picker Form Stuff Spinner Auto Complete Gallery 「Spinner」チュートリアルを日本語への翻訳と内容を補足しながらみていきます。 Spinner Spinnerの説明についてみていきます。 Spinner is a widget similar to a drop-down list for selecting items. In this tutorial, you'll create a simple spinner widget that displays a list of planets. When one is selected, a toast message will display the selected [...]]]></description>
			<content:encoded><![CDATA[<p><a href="http://developer.android.com/intl/ja/resources/tutorials/views/index.html" target="_blank">Android developers</a> による「Hello Views」チュートリアルで紹介されているウィジットには次のようなものがあります。</p>
<div style="border: 1px solid #c0c0c0; padding: 10px; margin-top: 20px;">
<ol>
<li>Date Picker</li>
<li>Time Picker</li>
<li>Form Stuff</li>
<li><span style="color: #ff0000;">Spinner</span></li>
<li>Auto Complete</li>
<li>Gallery</li>
</ol>
</div>
<p>「<a href="http://developer.android.com/intl/ja/resources/tutorials/views/hello-spinner.html" target="_blank">Spinner</a>」チュートリアルを日本語への翻訳と内容を補足しながらみていきます。</p>
<h2 style="padding-top: 40px; margin-bottom: 20px; padding-bottom: 0px;"><span style="color: #0000ff;">Spinner</span></h2>
<p>Spinnerの説明についてみていきます。</p>
<div style="border: 1px solid #c0c0c0; padding: 10px; margin-top: 20px;">
<p><code><a href="http://developer.android.com/reference/android/widget/Spinner.html" target="_blank">Spinner</a></code> is a widget similar to a drop-down list for selecting items.</p>
<p>In this tutorial, you'll create a simple spinner widget that displays a list of planets. When one is selected, a toast message will display the selected item.</p>
</div>
<p>[訳]</p>
<p><code><a href="http://developer.android.com/reference/android/widget/Spinner.html" target="_blank">Spinner</a></code>は、項目を選択するためのドロップダウンリストに似たウィジットです。</p>
<p>このチュートリアルでは、惑星のリストを表示する簡単なスピナーウィジットを作ります。1つが選択されたときに、トーストメッセージでその選択項目を表示します。</p>
<p><img class="aligncenter size-full wp-image-2221" title="android134" src="http://memories.zal.jp/WP/wp-content/uploads/2012/01/android134.jpg" alt="" width="300" height="72" /></p>
<p><span id="more-2218"></span></p>
<div class="title-blue-line-middle" style="margin-top: 50px;">プロジェクト</div>
<ul style="margin-left: 20px;">
<li>プロジェクト名（Project name）<span style="color: #0000ff;">HelloSpinner</span></li>
<li>内容(Contents)<span style="color: #0000ff;">ワークスペース内に新規プロジェクトを作成</span></li>
<li>ビルド・ターゲット(Build Target)<span style="color: #0000ff;">Android 1.6</span></li>
<li>アプリケーション名（Application Name）<span style="color: #0000ff;">HelloSpinner</span></li>
<li>パッケージ名（Package Name）<span style="color: #0000ff;">localhost.helloview</span></li>
<li>アクティビティの作成（Create Activity）<span style="color: #0000ff;">HelloSpinner</span></li>
<li>最小 SDKバージョン（Min SDK Version）<span style="color: #0000ff;">4</span></li>
</ul>
<p>プロジェクト作成については「<a href="http://memories.zal.jp/WP/20110508_2056.html" target="_blank">新規 Android プロジェクトを作成する</a>」の記事に詳しく書いたので参考にしてください。パッケージ名については公開するつもりもないので、とりあえずローカル環境用という意味合いで「localhost」にしました。</p>
<div class="title-blue-line-middle" style="margin-top: 50px;">レイアウトファイルの作成(main.xml)</div>
<div style="border: 1px solid #c0c0c0; padding: 10px; margin-top: 20px;">Open the <span style="color: #008000;"><code>res/layout/main.xml</code></span> file and insert the following:</div>
<p>[訳]</p>
<p><span style="color: #008000;">res/layout/main.xml</span> ファイルを開き、<code><code>次のコードを挿入します。</code></code></p>
<pre class="brush: java;">&lt;?xml version="1.0" encoding="utf-8"?&gt;
&lt;LinearLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:padding="10dip"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"&gt;
    &lt;TextView
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_marginTop="10dip"
        android:text="@string/planet_prompt"
    /&gt;
    &lt;Spinner
        android:id="@+id/spinner"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:prompt="@string/planet_prompt"
    /&gt;
&lt;/LinearLayout&gt;</pre>
<div style="border: 1px solid #c0c0c0; padding: 10px; margin-top: 20px;">Notice that the <code><a href="http://developer.android.com/reference/android/widget/TextView.html" target="_blank">TextView</a></code>'s <span style="color: #008000;"><code>android:text</code></span> attribute and the <code><a href="http://developer.android.com/reference/android/widget/Spinner.html" target="_blank">Spinner</a></code>'s <span style="color: #008000;"><code>android:prompt</code></span> attribute both reference the same string resource. This text behaves as a title for the widget. When applied to the <code><a href="http://developer.android.com/reference/android/widget/Spinner.html" target="_blank">Spinner</a></code>, the title text will appear in the selection dialog that appears upon selecting the widget.</div>
<p>[訳]</p>
<p><code><a href="http://developer.android.com/reference/android/widget/TextView.html" target="_blank">TextView</a></code>の <span style="color: #008000;"><code>android:text</code></span>属性と<code><a href="http://developer.android.com/reference/android/widget/Spinner.html" target="_blank">Spinner</a></code>の <span style="color: #008000;"><code>android:prompt</code></span>属性両方が、同じ文字列リソースを参照していることに注目してください。このテキストはウィジットのタイトルとして作用します。<code><a href="http://developer.android.com/reference/android/widget/Spinner.html" target="_blank">Spinner</a></code>に適用したとき、選択ダイアログ中にタイトルテキストが表示されます。この選択ダイアログは選択しているウィジット上に表示されます。</p>
<p><img class="aligncenter size-full wp-image-2222" style="margin-top: 30px; margin-bottom: 30px;" title="android135" src="http://memories.zal.jp/WP/wp-content/uploads/2012/01/android135.jpg" alt="" width="500" height="230" /></p>
<p><span style="color: #808080;">※この時点ではまだ@string/planet_prompt リソースを作成していません。エディターによっては「Not resource found ・・・・」のようなリソースが存在しない旨のエラーが表示されます。データリソースは、この後作成します。</span></p>
<div class="title-blue-line-middle" style="margin-top: 50px;">スピナーのデータを作成する(strings.xml)</div>
<div style="border: 1px solid #c0c0c0; padding: 10px; margin-top: 20px;">Create a <span style="color: #008000;"><code>strings.xml</code></span> file in <span style="color: #008000;"><code>res/values/</code></span> and edit the file to look like this:</div>
<p>[訳]</p>
<p><code><span style="color: #008000;"><code>res/values/</code></span>内に<span style="color: #008000;">strings.xml</span></code>ファイルを作って、このコードのようにファイルを編集してください。</p>
<pre class="brush: java;">&lt;?xml version="1.0" encoding="utf-8"?&gt;
&lt;resources&gt;
    &lt;string name="hello"&gt;Hello World, HelloSpinner!&lt;/string&gt;
    &lt;string name="app_name"&gt;HelloSpinner&lt;/string&gt;
    &lt;string name="planet_prompt"&gt;Choose a planet&lt;/string&gt;
    &lt;string-array name="planets_array"&gt;
        &lt;item&gt;Mercury&lt;/item&gt;
        &lt;item&gt;Venus&lt;/item&gt;
        &lt;item&gt;Earth&lt;/item&gt;
        &lt;item&gt;Mars&lt;/item&gt;
        &lt;item&gt;Jupiter&lt;/item&gt;
        &lt;item&gt;Saturn&lt;/item&gt;
        &lt;item&gt;Uranus&lt;/item&gt;
        &lt;item&gt;Neptune&lt;/item&gt;
    &lt;/string-array&gt;
&lt;/resources&gt;</pre>
<div style="border: 1px solid #c0c0c0; padding: 10px; margin-top: 20px;">The <span style="color: #008000;"><code>&lt;string&gt;</code></span> element defines the title string referenced by the <code><a href="http://developer.android.com/reference/android/widget/TextView.html" target="_blank">TextView</a></code> and <code><a href="http://developer.android.com/reference/android/widget/Spinner.html" target="_blank">Spinner</a></code> in the layout above. The <span style="color: #008000;"><code>&lt;string-array&gt;</code></span> element defines the list of strings that will be displayed as the list in the <code><a href="http://developer.android.com/reference/android/widget/Spinner.html" target="_blank">Spinner</a></code> widget.</div>
<p>[訳]</p>
<p><span style="color: #008000;"><code>&lt;string&gt;</code></span>要素は、上記のレイアウトの<code><a href="http://developer.android.com/reference/android/widget/TextView.html" target="_blank">TextView</a></code>と<code><a href="http://developer.android.com/reference/android/widget/Spinner.html" target="_blank">Spinner</a></code>によって参照されるタイトル文字列を定義します。<span style="color: #008000;"><code>&lt;string-array&gt;</code></span>要素は、<code><a href="http://developer.android.com/reference/android/widget/Spinner.html" target="_blank">Spinner</a></code>ウィジットのリストとして表示される文字列のリストを定義します。</p>
<p><img class="aligncenter size-full wp-image-2223" style="margin-top: 30px;" title="android136" src="http://memories.zal.jp/WP/wp-content/uploads/2012/01/android136.jpg" alt="" width="458" height="356" /></p>
<div class="title-blue-line-middle" style="margin-top: 50px;">アクティビティ作成(HelloSpinner.java)</div>
<div style="border: 1px solid #c0c0c0; padding: 10px; margin-top: 20px;">Now open the <span style="color: #008000;"><code>HelloSpinner.java</code></span> file and insert the following code for the <code><a href="http://developer.android.com/reference/android/app/Activity.html#onCreate%28android.os.Bundle%29" target="_blank">onCreate()</a></code> method:</div>
<p>[訳]</p>
<p>では、<span style="color: #008000;"><code>HelloSpinner.java</code></span>ファイルを開いて、次のコードを<code><a href="http://developer.android.com/reference/android/app/Activity.html#onCreate%28android.os.Bundle%29" target="_blank">onCreate()</a></code> メソッドに挿入してください。</p>
<p style="margin-bottom: 30px;">※チュートリアルでは追加部分だけ記載されていましたが、この記事ではHelloSpinner.java の全コードを記載しておきます。</p>
<pre class="brush: java;">package localhost.helloview;

import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.ArrayAdapter;
import android.widget.Spinner;
import android.widget.Toast;

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

	    Spinner spinner
	        = (Spinner) findViewById(R.id.spinner);
	    ArrayAdapter&lt;CharSequence&gt; adapter
	        = ArrayAdapter.createFromResource(
	                this, R.array.planets_array,
	                android.R.layout.simple_spinner_item
	             );
	    adapter.setDropDownViewResource(
	    		android.R.layout.simple_spinner_dropdown_item
	    	);
	    spinner.setAdapter(adapter);

	    spinner.setOnItemSelectedListener(
	    		new MyOnItemSelectedListener()
	    	);
	}

	public class MyOnItemSelectedListener implements OnItemSelectedListener {
	    public void onItemSelected(AdapterView&lt;?&gt; parent,
	        View view, int pos, long id) {
	      Toast.makeText(parent.getContext(), "The planet is " +
	          parent.getItemAtPosition(pos).toString(),
	          Toast.LENGTH_LONG).show();
	    }
	    public void onNothingSelected(AdapterView parent) {
	      // Do nothing.
	    }
	}
}</pre>
<div style="margin-top: 50px;">【19～29行目】</div>
<div style="border: 1px solid #c0c0c0; padding: 10px; margin-top: 3px;">After the <span style="color: #008000;"><code>main.xml</code></span> layout is set as the content view, the <code><a href="http://developer.android.com/reference/android/widget/Spinner.html" target="_blank">Spinner</a></code> widget is captured from the layout with <code><a href="http://developer.android.com/reference/android/app/Activity.html#findViewById%28int%29" target="_blank">findViewById(int)</a></code>. The <code><a href="http://developer.android.com/reference/android/widget/ArrayAdapter.html#createFromResource%28android.content.Context,%20int,%20int%29" target="_blank">createFromResource()</a></code> method then creates a new <code><a href="http://developer.android.com/reference/android/widget/ArrayAdapter.html" target="_blank">ArrayAdapter</a></code>, which binds each item in the string array to the initial appearance for the <code><a href="http://developer.android.com/reference/android/widget/Spinner.html" target="_blank">Spinner</a></code> (which is how each item will appear in the spinner when selected). The <span style="color: #008000;"><code>R.array.planets_array</code></span> ID references the <span style="color: #008000;"><code>string-array</code></span> defined above and the <span style="color: #008000;"><code>android.R.layout.simple_spinner_item</code></span> ID references a layout for the standard spinner appearance, defined by the platform. Then <code><a href="http://developer.android.com/reference/android/widget/ArrayAdapter.html#setDropDownViewResource%28int%29" target="_blank">setDropDownViewResource(int)</a></code> is called to define the appearance for each item when the widget is opened (<span style="color: #008000;"><code>simple_spinner_dropdown_item</code></span> is another standard layout defined by the platform). Finally, the <code><a href="http://developer.android.com/reference/android/widget/ArrayAdapter.html" target="_blank">ArrayAdapter</a></code> is set to associate all of its items with the <code><a href="http://developer.android.com/reference/android/widget/Spinner.html" target="_blank">Spinner</a></code> by calling <code><a href="http://developer.android.com/reference/android/widget/AdapterView.html#setAdapter%28T%29" target="_blank">setAdapter(T)</a></code>.</div>
<p>[訳]</p>
<p><span style="color: #008000;"><code>main.xml</code></span>がコンテントビューとして設定された後、<code><a href="http://developer.android.com/reference/android/widget/Spinner.html" target="_blank">Spinner</a></code>ウィジットをレイアウトから <code><a href="http://developer.android.com/reference/android/app/Activity.html#findViewById%28int%29" target="_blank">findViewById(int)</a></code>メソッドを使って取得します。それから<code><a href="http://developer.android.com/reference/android/widget/ArrayAdapter.html#createFromResource%28android.content.Context,%20int,%20int%29" target="_blank">createFromResource()</a></code>メソッドにより新規に<code><a href="http://developer.android.com/reference/android/widget/ArrayAdapter.html" target="_blank">ArrayAdapter</a></code>を生成します。<code><a href="http://developer.android.com/reference/android/widget/ArrayAdapter.html" target="_blank">ArrayAdapter</a></code>は文字列配列のそれぞれの項目をバインドし、<code><a href="http://developer.android.com/reference/android/widget/Spinner.html" target="_blank">Spinner</a></code>の最初の外観になります（選択されたときに、それぞれの項目がスピナー上でどのように表示されるかを決めます）。 <span style="color: #008000;"><code>R.array.planets_array</code></span> IDは、上記で定義した<span style="color: #008000;"><code>string-array</code></span>を参照し、<span style="color: #008000;"><code>android.R.layout.simple_spinner_item</code></span> IDは、プラットフォームによって定義された標準のスピナー外観であるレイアウトを参照します。それから<code><a href="http://developer.android.com/reference/android/widget/ArrayAdapter.html#setDropDownViewResource%28int%29" target="_blank">setDropDownViewResource(int)</a></code> が呼ばれ、ウィジットが開かれたときのそれぞれの項目の外観を定義します（<span style="color: #008000;"><code>simple_spinner_dropdown_item</code></span>は、プラットフォームで定義された別の標準レイアウトです）。最後に、項目のすべてを<code><a href="http://developer.android.com/reference/android/widget/Spinner.html" target="_blank">Spinner</a></code>と関連づけるため、<code><a href="http://developer.android.com/reference/android/widget/AdapterView.html#setAdapter%28T%29" target="_blank">setAdapter(T)</a></code>を呼び<code><a href="http://developer.android.com/reference/android/widget/ArrayAdapter.html" target="_blank">ArrayAdapter</a></code>をセットします。</p>
<div style="margin-top: 30px;">[補足]<br />
22行目のcreateFromResourceは外部リソースからArrayAdapterインスタンスを生成するメソッドです。</p>
<ul>
<li>パラメータ
<ol>
<li>第1パラメータは、コンテキストを指定します。コンテキストとはアプリケーション環境についてのグローバル情報のインターフェースです。Activity内で使う場合は、Activity がContextを継承している為、thisが使えます。コンテキストについては「<a href="http://individualmemo.blog104.fc2.com/blog-entry-41.html" target="_blank">整理できない底辺プログラマのメモブログ &gt; Contextとは?</a>」が参考になりました。</li>
<li>第2パラメータは、データソースとして使う為の配列のリソースを指定しています。</li>
<li>第3パラメータは、生成するビューに使うレイアウトのリソースを指定しています。</li>
</ol>
</li>
<li>戻り値<br />
ArrayAdapter</li>
</ul>
</div>
<div style="margin-top: 50px;">【36～46行目】</div>
<div style="border: 1px solid #c0c0c0; padding: 10px; margin-top: 3px;">Now create a nested class that implements <code><a href="http://developer.android.com/reference/android/widget/AdapterView.OnItemSelectedListener.html" target="_blank">AdapterView.OnItemSelectedListener</a></code>. This will provide a callback method that will notify your application when an item has been selected from the <code><a href="http://developer.android.com/reference/android/widget/Spinner.html" target="_blank">Spinner</a></code>.The <code><a href="http://developer.android.com/reference/android/widget/AdapterView.OnItemSelectedListener.html" target="_blank">AdapterView.OnItemSelectedListener</a></code> requires the <code><a href="http://developer.android.com/reference/android/widget/AdapterView.OnItemSelectedListener.html#onItemSelected%28android.widget.AdapterView%3C?%3E,%20android.view.View,%20int,%20long%29" target="_blank">onItemSelected()</a></code> and <code><a href="http://developer.android.com/reference/android/widget/AdapterView.OnItemSelectedListener.html#onNothingSelected%28android.widget.AdapterView%3C?%3E%29" target="_blank">onNothingSelected()</a></code> callback methods. The former is called when an item from the <code><a href="http://developer.android.com/reference/android/widget/AdapterView.html" target="_blank">AdapterView</a></code> is selected, in which case, a short <code><a href="http://developer.android.com/reference/android/widget/Toast.html" target="_blank">Toast</a></code> message displays the selected text; and the latter is called when a selection disappears from the <code><a href="http://developer.android.com/reference/android/widget/AdapterView.html" target="_blank">AdapterView</a></code>, which doesn't happen in this case, so it's ignored.</div>
<p>[訳]</p>
<p>では、<code><a href="http://developer.android.com/reference/android/widget/AdapterView.OnItemSelectedListener.html" target="_blank">AdapterView.OnItemSelectedListener</a></code> を実装した内部クラスを作ります。これは、スピナーから項目が選択されたときアプリケーションに通知するコールバックメソッドを提供します。<code><a href="http://developer.android.com/reference/android/widget/AdapterView.OnItemSelectedListener.html" target="_blank">AdapterView.OnItemSelectedListenerに</a></code>は、<code><a href="http://developer.android.com/reference/android/widget/AdapterView.OnItemSelectedListener.html#onItemSelected%28android.widget.AdapterView%3C?%3E,%20android.view.View,%20int,%20long%29" target="_blank">onItemSelected()</a></code>と<code><a href="http://developer.android.com/reference/android/widget/AdapterView.OnItemSelectedListener.html#onNothingSelected%28android.widget.AdapterView%3C?%3E%29" target="_blank">onNothingSelected()</a></code> コールバックメソッドが必要になります。前者は、<code><a href="http://developer.android.com/reference/android/widget/AdapterView.html" target="_blank">AdapterView</a></code>から項目が選択されたとき呼ばれます。この場合、選択されたテキストが短い<code><a href="http://developer.android.com/reference/android/widget/Toast.html" target="_blank">Toast</a></code>メッセージで表示されます。そして後者は、<code><a href="http://developer.android.com/reference/android/widget/AdapterView.html" target="_blank">AdapterView</a></code>から選択がなくなったとき呼ばれますが、この場合は起こらないので無視されます。</p>
<div style="margin-top: 50px;">【31～32行目】</div>
<div style="border: 1px solid #c0c0c0; padding: 10px; margin-top: 3px;">
<p>Now the <span style="color: #008000;"><code>MyOnItemSelectedListener</code></span> needs to be applied to the <code><a href="http://developer.android.com/reference/android/widget/Spinner.html" target="_blank">Spinner</a></code>.</p>
<p>This creates a new anonymous instance of the <span style="color: #008000;"><code>MyOnItemSelectedListener</code></span> and sets it as the listener for the <code><a href="http://developer.android.com/reference/android/widget/Spinner.html">Spinner</a></code>.</p>
</div>
<p>[訳]</p>
<p>では、<span style="color: #008000;"><code>MyOnItemSelectedListener</code></span>を<code><a href="http://developer.android.com/reference/android/widget/Spinner.html" target="_blank">Spinner</a></code>に適用しなければなりません。</p>
<p>ここでは新しい<span style="color: #008000;"><code>MyOnItemSelectedListener</code></span>の匿名インスタンスを作り、それを<code><a href="http://developer.android.com/reference/android/widget/Spinner.html">Spinner</a></code>のリスナーとしてセットしています。</p>
<div class="title-blue-line-middle" style="margin-top: 50px;">AVDによる実行</div>
<p>AVDによるアプリケーションの実行については「<a href="http://memories.zal.jp/WP/20110516_2073.html#app_excute" target="_blank">AVDでアプリケーションを実行する</a>」の記事で詳しく書きました。参考にしてください。</p>
<p>実行結果をみてみます。次のような画面が表示されました。</p>
<p><img class="aligncenter size-full wp-image-2220" title="android133" src="http://memories.zal.jp/WP/wp-content/uploads/2012/01/android133.jpg" alt="" width="550" height="320" /></p>
]]></content:encoded>
			<wfw:commentRss>http://memories.zal.jp/WP/blog/20120123_2218.html/feed</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>レーティングバー/Form Stuff について</title>
		<link>http://memories.zal.jp/WP/blog/20111230_2203.html</link>
		<comments>http://memories.zal.jp/WP/blog/20111230_2203.html#comments</comments>
		<pubDate>Fri, 30 Dec 2011 12:51:37 +0000</pubDate>
		<dc:creator>admin</dc:creator>
				<category><![CDATA[Android]]></category>
		<category><![CDATA[Hello_Views]]></category>

		<guid isPermaLink="false">http://memories.zal.jp/WP/?p=2203</guid>
		<description><![CDATA[Android developers による「Hello Views」チュートリアルで紹介されているウィジットには次のようなものがあります。 Date Picker Time Picker Form Stuff Ｌ Custom Button Ｌ Edit Text Ｌ Checkbox Ｌ Radio Buttons Ｌ Toggle Button Ｌ Rating Bar Spinner Auto Complete Gallery 「Form Stuff」チュートリアルを日本語への翻訳と内容を補足しながらみていきます。今回はRating Barについてみていきます。 Rating Bar Rating Barの説明についてみていきます。 In this section, you'll create a widget that allows the user to provide a rating, with the RatingBar widget. [訳] このセクションではRatingBar ウィジットを使って、ユーザがレーティングできるウィジットを作ります。 [...]]]></description>
			<content:encoded><![CDATA[<p><a href="http://developer.android.com/intl/ja/resources/tutorials/views/index.html" target="_blank">Android developers</a> による「Hello Views」チュートリアルで紹介されているウィジットには次のようなものがあります。</p>
<div style="border: 1px solid #c0c0c0; padding: 10px; margin-top: 20px;">
<ol>
<li>Date Picker</li>
<li>Time Picker</li>
<li>Form Stuff<br />
<span style="padding-left: 10px;">Ｌ Custom Button</span><br />
<span style="padding-left: 10px;">Ｌ Edit Text</span><br />
<span style="padding-left: 10px;">Ｌ Checkbox</span><br />
<span style="padding-left: 10px;">Ｌ Radio Buttons</span><br />
<span style="padding-left: 10px;">Ｌ Toggle Button</span><br />
<span style="padding-left: 10px;">Ｌ <span style="color: #ff0000;">Rating Bar</span></span></li>
<li>Spinner</li>
<li>Auto Complete</li>
<li>Gallery</li>
</ol>
</div>
<p>「<a href="http://developer.android.com/intl/ja/resources/tutorials/views/hello-formstuff.html" target="_blank">Form Stuff</a>」チュートリアルを日本語への翻訳と内容を補足しながらみていきます。今回はRating Barについてみていきます。</p>
<h2 style="padding-top: 40px; margin-bottom: 20px; padding-bottom: 0px;"><span style="color: #0000ff;">Rating Bar</span></h2>
<p>Rating Barの説明についてみていきます。</p>
<div style="border: 1px solid #c0c0c0; padding: 10px; margin-top: 20px;">In this section, you'll create a widget that allows the user to provide a rating, with the <code><a href="http://developer.android.com/reference/android/widget/RatingBar.html" target="_blank">RatingBar</a></code> widget.</div>
<p>[訳]<br />
このセクションでは<code><a href="http://developer.android.com/reference/android/widget/RatingBar.html" target="_blank">RatingBar</a></code> ウィジットを使って、ユーザがレーティングできるウィジットを作ります。</p>
<p><img class="aligncenter size-full wp-image-2215" title="android130" src="http://memories.zal.jp/WP/wp-content/uploads/2011/12/android130.jpg" alt="" width="300" height="104" /></p>
<p><span id="more-2203"></span></p>
<div class="title-blue-line-middle" style="margin-top: 50px;">プロジェクト</div>
<p>AndroidチュートリアルではCustom Button、Edit Text、Checkbox、Radio Buttons、Toggle Button、<span style="color: #ff0000;">Rating Bar</span>は1つのプロジェクト内で説明していますが、このブログでは各フォーム要素ごとにプロジェクトを作成します。</p>
<ul style="margin-left: 20px;">
<li>プロジェクト名（Project name）<br />
<span style="color: #0000ff;">FormStuffRatingBar</span></li>
<li>内容(Contents)<br />
<span style="color: #0000ff;">ワークスペース内に新規プロジェクトを作成</span></li>
<li>ビルド・ターゲット(Build Target)<br />
<span style="color: #0000ff;">Android 1.6</span></li>
<li>アプリケーション名（Application Name）<br />
<span style="color: #0000ff;">FormStuffRatingBar</span></li>
<li>パッケージ名（Package Name）<br />
<span style="color: #0000ff;">localhost.helloview</span></li>
<li>アクティビティの作成（Create Activity）<br />
<span style="color: #0000ff;">FormStuffRatingBar</span></li>
<li>最小 SDKバージョン（Min SDK Version）<br />
<span style="color: #0000ff;">4</span></li>
</ul>
<p>プロジェクト作成については「<a href="http://memories.zal.jp/WP/20110508_2056.html" target="_blank">新規 Android プロジェクトを作成する</a>」の記事に詳しく書いたので参考にしてください。パッケージ名については公開するつもりもないので、とりあえずローカル環境用という意味合いで「localhost」にしました。</p>
<div class="title-blue-line-middle" style="margin-top: 50px;">レイアウトファイルの作成(main.xml)</div>
<div style="border: 1px solid #c0c0c0; padding: 10px; margin-top: 20px;">Open the <span style="color: #339966;"><code>res/layout/main.xml</code></span> file and add the <code><a href="http://developer.android.com/reference/android/widget/RatingBar.html" target="_blank">RatingBar</a></code> element (inside the <code><a href="http://developer.android.com/reference/android/widget/LinearLayout.html" target="_blank">LinearLayout</a></code>):</div>
<p>[訳]<br />
<span style="color: #008000;">res/layout/main.xml</span> ファイルを開き、<code><code><a href="http://developer.android.com/reference/android/widget/RatingBar.html" target="_blank">RatingBar</a></code> </code>要素を追加します（<code><a href="http://developer.android.com/reference/android/widget/LinearLayout.html" target="_blank">LinearLayout</a></code>の中に）。</p>
<pre class="brush: java;">&lt;?xml version="1.0" encoding="utf-8"?&gt;
&lt;LinearLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    &gt;
    &lt;RatingBar android:id="@+id/ratingbar"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:numStars="5"
        android:stepSize="1.0"/&gt;
&lt;/LinearLayout&gt;</pre>
<p style="margin-bottom: 30px;">※チュートリアルではエレメントの追加部分だけ記載されていましたが、この記事ではres/layout/main.xml の全コードを記載しておきます。</p>
<div style="border: 1px solid #c0c0c0; padding: 10px; margin-top: 20px;">The <span style="color: #008000;"><code>android:numStars</code></span> attribute defines how many stars to display for the rating bar. The <span style="color: #008000;"><code>android:stepSize</code></span> attribute defines the granularity for each star (for example, a value of <span style="color: #008000;"><code>0.5</code></span> would allow half-star ratings).</div>
<p>[訳]<br />
<span style="color: #008000;">android:numStars</span>属性ではレーティングバーに星をいくつ表示するのか定義します。<span style="color: #008000;">android:stepSize</span>属性は各星の粒度を定義します（例えば0.5の値は星半分のレーティングになります）。</p>
<p><img class="aligncenter size-full wp-image-2216" title="android131" src="http://memories.zal.jp/WP/wp-content/uploads/2011/12/android131.jpg" alt="" width="450" height="94" /></p>
<div class="title-blue-line-middle" style="margin-top: 50px;">アクティビティ作成(FormStuffRatingBar.java)</div>
<div style="border: 1px solid #c0c0c0; padding: 10px; margin-top: 20px;">To do something when the state is changed, add the following code to the end of the <code><a href="http://developer.android.com/reference/android/app/Activity.html#onCreate%28android.os.Bundle%29" target="_blank">onCreate()</a></code> method:</div>
<p>[訳]<br />
新しいレーティングが設定されたときに何らかの処理をさせるためには、<code><a href="http://developer.android.com/reference/android/app/Activity.html#onCreate%28android.os.Bundle%29" target="_blank">onCreate</a></code> メソッドの最後に次のコードを追加します。</p>
<p style="margin-bottom: 30px;">※チュートリアルでは追加部分だけ記載されていましたが、この記事ではFormStuffRatingBar.java の全コードを記載しておきます。</p>
<pre class="brush: java;">package localhost.helloview;

import android.app.Activity;
import android.os.Bundle;
import android.widget.RatingBar;
import android.widget.RatingBar.OnRatingBarChangeListener;
import android.widget.Toast;

public class FormStuffRatingBar extends Activity {
    /** アクティビティが最初に作られたときに呼ばれる */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);

        //レイアウトからRatingBarインスタンス生成
        final RatingBar ratingbar
            = (RatingBar) findViewById(R.id.ratingbar);
        //RatingBarインスタンスにリスナー追加
        ratingbar.setOnRatingBarChangeListener(new OnRatingBarChangeListener() {
            //レーティングが変化した場合
        	public void onRatingChanged(
            		RatingBar ratingBar,
            		float rating,
            		boolean fromUser
            ) {
        		//トーストメッセージ表示
                Toast.makeText(
                	FormStuffRatingBar.this,
                	"New Rating: " + rating,
                	Toast.LENGTH_SHORT).show();
            }
        });
    }
}</pre>
<div style="border: 1px solid #c0c0c0; padding: 10px; margin-top: 20px;">This captures the <code><a href="http://developer.android.com/reference/android/widget/RatingBar.html" target="_blank">RatingBar</a></code> widget from the layout with <code><a href="http://developer.android.com/reference/android/app/Activity.html#findViewById%28int%29" target="_blank">findViewById(int)</a></code> and then sets an <code><a href="http://developer.android.com/reference/android/widget/RatingBar.OnRatingBarChangeListener.html" target="_blank">RatingBar.OnRatingBarChangeListener</a></code>. The <code><a href="http://developer.android.com/reference/android/widget/RatingBar.OnRatingBarChangeListener.html#onRatingChanged%28android.widget.RatingBar,%20float,%20boolean%29" target="_blank">onRatingChanged()</a></code> callback method then defines the action to perform when the user sets a rating. In this case, a simple <code><a href="http://developer.android.com/reference/android/widget/Toast.html" target="_blank">Toast</a></code> message displays the new rating.</div>
<p>[訳]<br />
ここでは<code><a href="http://developer.android.com/reference/android/app/Activity.html#findViewById%28int%29" target="_blank">findViewById(int)</a></code>を使ってレイアウトから<code><a href="http://developer.android.com/reference/android/widget/RatingBar.html" target="_blank">RatingBar</a></code> ウィジットを取得します。それから<code><a href="http://developer.android.com/reference/android/widget/RatingBar.OnRatingBarChangeListener.html" target="_blank">RatingBar.OnRatingBarChangeListener</a></code>を設定します。<code><a href="http://developer.android.com/reference/android/widget/RatingBar.OnRatingBarChangeListener.html#onRatingChanged%28android.widget.RatingBar,%20float,%20boolean%29" target="_blank">onRatingChanged()</a></code> コールバックメソッドはユーザがレーティングを設定したときに実行されるアクションを定義します。このケースでは、新しいレーティング状態が単純な<code><a href="http://developer.android.com/reference/android/widget/Toast.html" target="_blank">Toast</a></code>メッセージで表示されます。</p>
<p><img class="aligncenter size-full wp-image-2217" title="android132" src="http://memories.zal.jp/WP/wp-content/uploads/2011/12/android132.jpg" alt="" width="400" height="67" /></p>
<div style="margin-top: 30px;">【補足】</div>
<ul>
<li>17行目ではレイアウトからRatingBarインスタンスを生成しています。</li>
<li>20行目ではsetOnRatingBarChangeListenerメソッドによりレーティングが変化したときに呼ばれるリスナーをセットしています。またパラメータのOnRatingBarChangeListenerはインターフェースであり、レーティングが変化したときにクライアントに通知するコールバックを作ります。このインターフェースを実装したらonRatingChangedメソッドをオーバーライドする必要があります。<br />
<span style="color: #888888; font-size: 10px;">※参考：<a href="http://developer.android.com/intl/ja/reference/android/widget/RatingBar.OnRatingBarChangeListener.html" target="_blank">RatingBar.OnRatingBarChangeListener</a></span></li>
<li>22行目でonRatingChangedをオーバーライドしています。</li>
<li>28～31行目で現状のレーティング状態をトーストで表示しています。</li>
</ul>
<div class="title-blue-line-middle" style="margin-top: 50px;">AVDによる実行</div>
<p>AVDによるアプリケーションの実行については「<a href="http://memories.zal.jp/WP/20110516_2073.html#app_excute" target="_blank">AVDでアプリケーションを実行する</a>」の記事で詳しく書きました。参考にしてください。</p>
<p>実行結果をみてみます。次のような画面が表示されました。</p>
<p><img class="aligncenter size-full wp-image-2212" title="android129" src="http://memories.zal.jp/WP/wp-content/uploads/2011/12/android129.jpg" alt="" width="500" height="461" /></p>
]]></content:encoded>
			<wfw:commentRss>http://memories.zal.jp/WP/blog/20111230_2203.html/feed</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>トグルボタン/Form Stuff について</title>
		<link>http://memories.zal.jp/WP/blog/20111223_2197.html</link>
		<comments>http://memories.zal.jp/WP/blog/20111223_2197.html#comments</comments>
		<pubDate>Fri, 23 Dec 2011 08:51:58 +0000</pubDate>
		<dc:creator>admin</dc:creator>
				<category><![CDATA[Android]]></category>
		<category><![CDATA[Hello_Views]]></category>

		<guid isPermaLink="false">http://memories.zal.jp/WP/?p=2197</guid>
		<description><![CDATA[Android developers による「Hello Views」チュートリアルで紹介されているウィジットには次のようなものがあります。 Date Picker Time Picker Form Stuff Ｌ Custom Button Ｌ Edit Text Ｌ Checkbox Ｌ Radio Buttons Ｌ Toggle Button Ｌ Rating Bar Spinner Auto Complete Gallery 「Form Stuff」チュートリアルを日本語への翻訳と内容を補足しながらみていきます。今回はToggle Buttonについてみていきます。 Toggle Button Radio Buttonsの説明についてみていきます。 In this section, you'll create a button used specifically for toggling between two states, using the ToggleButton widget. This widget is an [...]]]></description>
			<content:encoded><![CDATA[<p><a href="http://developer.android.com/intl/ja/resources/tutorials/views/index.html" target="_blank">Android developers</a> による「Hello Views」チュートリアルで紹介されているウィジットには次のようなものがあります。</p>
<div style="border: 1px solid #c0c0c0; padding: 10px; margin-top: 20px;">
<ol>
<li>Date Picker</li>
<li>Time Picker</li>
<li>Form Stuff<br />
<span style="padding-left: 10px;">Ｌ Custom Button</span><br />
<span style="padding-left: 10px;">Ｌ Edit Text</span><br />
<span style="padding-left: 10px;">Ｌ Checkbox</span><br />
<span style="padding-left: 10px;">Ｌ Radio Buttons</span><br />
<span style="padding-left: 10px;">Ｌ <span style="color: #ff0000;">Toggle Button</span></span><br />
<span style="padding-left: 10px;">Ｌ Rating Bar</span></li>
<li>Spinner</li>
<li>Auto Complete</li>
<li>Gallery</li>
</ol>
</div>
<p>「<a href="http://developer.android.com/intl/ja/resources/tutorials/views/hello-formstuff.html" target="_blank">Form Stuff</a>」チュートリアルを日本語への翻訳と内容を補足しながらみていきます。今回はToggle Buttonについてみていきます。</p>
<h2 style="padding-top: 40px; margin-bottom: 20px; padding-bottom: 0px;"><span style="color: #0000ff;">Toggle Button</span></h2>
<p>Radio Buttonsの説明についてみていきます。</p>
<div style="border: 1px solid #c0c0c0; padding: 10px; margin-top: 20px;">In this section, you'll create a button used specifically for toggling between two states, using the <code><a href="http://developer.android.com/reference/android/widget/ToggleButton.html" target="_blank">ToggleButton</a></code> widget. This widget is an excellent alternative to radio buttons if you have two simple states that are mutually exclusive ("on" and "off", for example).</div>
<p>[訳]<br />
このセクションでは<code><a href="http://developer.android.com/reference/android/widget/ToggleButton.html" target="_blank">ToggleButton</a> </code>ウィジットを使って、特に２つの状態を切り替えるトグルに使われるボタンを作ります。このウィジットは、互いに排他的な２つの単純な状態（例えば"on"と"off")を持っているときにラジオボタンの変わりとして使うには優秀です。</p>
<p><img class="aligncenter size-full wp-image-2200" title="android128" src="http://memories.zal.jp/WP/wp-content/uploads/2011/12/android128.jpg" alt="" width="200" height="69" /><span id="more-2197"></span></p>
<div class="title-blue-line-middle" style="margin-top: 50px;">プロジェクト</div>
<p>AndroidチュートリアルではCustom Button、Edit Text、Checkbox、Radio Buttons、<span style="color: #ff0000;">Toggle Button</span>、Rating Barは1つのプロジェクト内で説明していますが、このブログでは各フォーム要素ごとにプロジェクトを作成します。</p>
<ul style="margin-left: 20px;">
<li>プロジェクト名（Project name）<br />
<span style="color: #0000ff;">FormStuffToggleButton</span></li>
<li>内容(Contents)<br />
<span style="color: #0000ff;">ワークスペース内に新規プロジェクトを作成</span></li>
<li>ビルド・ターゲット(Build Target)<br />
<span style="color: #0000ff;">Android 1.6</span></li>
<li>アプリケーション名（Application Name）<br />
<span style="color: #0000ff;">FormStuffToggleButton</span></li>
<li>パッケージ名（Package Name）<br />
<span style="color: #0000ff;">localhost.helloview</span></li>
<li>アクティビティの作成（Create Activity）<br />
<span style="color: #0000ff;">FormStuffToggleButton</span></li>
<li>最小 SDKバージョン（Min SDK Version）<br />
<span style="color: #0000ff;">4</span></li>
</ul>
<p>プロジェクト作成については「<a href="http://memories.zal.jp/WP/20110508_2056.html" target="_blank">新規 Android プロジェクトを作成する</a>」の記事に詳しく書いたので参考にしてください。パッケージ名については公開するつもりもないので、とりあえずローカル環境用という意味合いで「localhost」にしました。</p>
<div class="title-blue-line-middle" style="margin-top: 50px;">レイアウトファイルの作成(main.xml)</div>
<div style="border: 1px solid #c0c0c0; padding: 10px; margin-top: 20px;">Open the <span style="color: #008000;"><code>res/layout/main.xml</code></span> file and add the <code><a href="http://developer.android.com/reference/android/widget/ToggleButton.html" target="_blank">ToggleButton</a></code> element (inside the <code><a href="http://developer.android.com/reference/android/widget/LinearLayout.html" target="_blank">LinearLayout</a></code>):</div>
<p>[訳]<br />
<span style="color: #008000;">res/layout/main.xml</span> ファイルを開き、<code><a href="http://developer.android.com/reference/android/widget/ToggleButton.html" target="_blank">ToggleButton</a></code>要素を追加します（<code><a href="http://developer.android.com/reference/android/widget/LinearLayout.html" target="_blank">LinearLayout</a></code>の中に）。</p>
<pre class="brush: java;">&lt;?xml version="1.0" encoding="utf-8"?&gt;
&lt;LinearLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    &gt;
    &lt;ToggleButton android:id="@+id/togglebutton"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textOn="Vibrate on"
        android:textOff="Vibrate off"/&gt;
&lt;/LinearLayout&gt;</pre>
<p style="margin-bottom: 30px;">※チュートリアルではエレメントの追加部分だけ記載されていましたが、この記事ではres/layout/main.xml の全コードを記載しておきます。</p>
<div style="border: 1px solid #c0c0c0; padding: 10px; margin-top: 20px;">The attributes <span style="color: #008000;"><code>android:textOn</code></span> and <span style="color: #008000;"><code>android:textOff</code></span> specify the text for the button when the button has been toggled on or off. The default values are "ON" and "OFF".</div>
<p>[訳]<br />
属性<span style="color: #008000;">android:textOn</span> と <span style="color: #008000;">android:textOff </span>はボタンがonやoffの状態にトグルされたときに、ボタンに表示するテキストを明示します。デフォルト値は"On"と"Off"です。</p>
<p><img class="aligncenter size-full wp-image-2199" title="android127" src="http://memories.zal.jp/WP/wp-content/uploads/2011/12/android127.jpg" alt="" width="430" height="121" /></p>
<div class="title-blue-line-middle" style="margin-top: 50px;">アクティビティ作成(FormStuffToggleButton.java)</div>
<div style="border: 1px solid #c0c0c0; padding: 10px; margin-top: 20px;">To do something when the state is changed, add the following code to the end of the <code><a href="http://developer.android.com/reference/android/app/Activity.html#onCreate%28android.os.Bundle%29" target="_blank">onCreate()</a></code> method:</div>
<p>[訳]<br />
状態が変化したときに何らかの処理をさせるためには、<code><a href="http://developer.android.com/reference/android/app/Activity.html#onCreate%28android.os.Bundle%29" target="_blank">onCreate</a> </code>メソッドの最後に次のコードを追加します。</p>
<p style="margin-bottom: 30px;">※チュートリアルでは追加部分だけ記載されていましたが、この記事ではFormStuffToggleButton.java の全コードを記載しておきます。</p>
<pre class="brush: java;">package localhost.helloview;

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

public class FormStuffToggleButton extends Activity {
    /** アクティビティが最初に作られたときに呼ばれます */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);

        //レイアウトからToggleButtonインスタンス生成
        final ToggleButton togglebutton = (ToggleButton) findViewById(R.id.togglebutton);
        //イベントリスナー追加
        togglebutton.setOnClickListener(new OnClickListener() {
            //トグルボタンがクリックされたとき
        	public void onClick(View v) {
                //チェックON状態
                if (togglebutton.isChecked()) {
                    Toast.makeText(
                    	FormStuffToggleButton.this,
                    	"Checked",
                    	Toast.LENGTH_SHORT).show();
                }
                //チェックOFF状態
                else {
                    Toast.makeText(
                    	FormStuffToggleButton.this,
                    	"Not checked",
                    	Toast.LENGTH_SHORT).show();
                }
            }
        });
    }
}</pre>
<div style="border: 1px solid #c0c0c0; padding: 10px; margin-top: 20px;">
<p>This captures the <code><a href="http://developer.android.com/reference/android/widget/ToggleButton.html" target="_blank">ToggleButton</a></code> element from the layout, then adds an <code><a href="http://developer.android.com/reference/android/view/View.OnClickListener.html" target="_blank">View.OnClickListener</a></code>. The <code><a href="http://developer.android.com/reference/android/view/View.OnClickListener.html" target="_blank">View.OnClickListener</a></code> must implement the <code><a href="http://developer.android.com/reference/android/view/View.OnClickListener.html#onClick%28android.view.View%29" target="_blank">onClick(View)</a></code> callback method, which defines the action to perform when the button is clicked. In this example, the callback method checks the new state of the button, then shows a <code><a href="http://developer.android.com/reference/android/widget/Toast.html">Toast</a></code> message that indicates the current state.</p>
<p>Notice that the <code><a href="http://developer.android.com/reference/android/widget/ToggleButton.html" target="_blank">ToggleButton</a></code> handles its own state change between checked and unchecked, so you just ask which it is.</p>
</div>
<p>[訳]<br />
ここではレイアウトから<code><a href="http://developer.android.com/reference/android/widget/ToggleButton.html" target="_blank">ToggleButton</a></code>エレメントを取得し、それから<code><a href="http://developer.android.com/reference/android/view/View.OnClickListener.html" target="_blank">View.OnClickListener</a> </code>を付与します。<code><a href="http://developer.android.com/reference/android/view/View.OnClickListener.html" target="_blank">View.OnClickListener</a> </code>は<code><a href="http://developer.android.com/reference/android/view/View.OnClickListener.html#onClick%28android.view.View%29" target="_blank">onClick(View)</a> </code>コールバックメソッドを実装しなければなりません。このメソッドではボタンがクリックされたときに実行するアクションを定義します。サンプルでは、コールバックメソッドがボタンの新しい状態をチェックし、現在の状態を示すトーストメッセージを表示します。</p>
<p><code><a href="http://developer.android.com/reference/android/widget/ToggleButton.html" target="_blank">ToggleButton </a>は自分自身でチェックされているかされていないかの状態変化をハンドルするので、ただ状態がどっちなのか尋ねるだけでいいことに注目してください。</code></p>
<div style="margin-top: 30px;">【補足】</div>
<ul>
<li>18行目ではレイアウトからToggleButtonインスタンスを生成しています。</li>
<li>20行目で<code><a href="http://developer.android.com/reference/android/view/View.OnClickListener.html" target="_blank">OnClickListener</a></code><code>のインスタンスを生成しています。</code><code><a href="http://developer.android.com/reference/android/view/View.OnClickListener.html" target="_blank">OnClickListener</a></code>はインターフェースなので実装する場合は<code><a href="http://developer.android.com/reference/android/view/View.OnClickListener.html#onClick%28android.view.View%29" target="_blank">onClick</a></code>メソッドをオーバーライドしなければなりません。<br />
<span style="color: #888888; font-size: 10px;">※参考：<a href="http://developer.android.com/reference/android/view/View.OnClickListener.html" target="_blank">android.view.OnClickListener</a></span></li>
<li>22行目でonClickメソッドをオーバーライドしています。onClickメソッドはViewがクリックされたときに呼ばれます。パラメータとして渡されるのはクリックされたViewインスタンスです。</li>
<li>23～29行目でトグルボタンがON状態に変わったときの処理が書かれています。"Checked"のメッセージがトーストで表示されます。</li>
<li>30～36行目でトグルボタンがOFF状態に変わったときの処理が書かれています。"Not checked"のメッセージがトーストで表示されます。</li>
</ul>
<div class="title-blue-line-middle" style="margin-top: 50px;">AVDによる実行</div>
<p>AVDによるアプリケーションの実行については「<a href="http://memories.zal.jp/WP/20110516_2073.html#app_excute" target="_blank">AVDでアプリケーションを実行する</a>」の記事で詳しく書きました。参考にしてください。</p>
<p>実行結果をみてみます。次のような画面が表示されました。</p>
<p><img class="aligncenter size-full wp-image-2198" title="android126" src="http://memories.zal.jp/WP/wp-content/uploads/2011/12/android126.jpg" alt="" width="500" height="460" /></p>
]]></content:encoded>
			<wfw:commentRss>http://memories.zal.jp/WP/blog/20111223_2197.html/feed</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>ラジオボタン/Form Stuff について</title>
		<link>http://memories.zal.jp/WP/blog/20111218_2194.html</link>
		<comments>http://memories.zal.jp/WP/blog/20111218_2194.html#comments</comments>
		<pubDate>Sun, 18 Dec 2011 14:47:02 +0000</pubDate>
		<dc:creator>admin</dc:creator>
				<category><![CDATA[Android]]></category>
		<category><![CDATA[Hello_Views]]></category>

		<guid isPermaLink="false">http://memories.zal.jp/WP/?p=2194</guid>
		<description><![CDATA[Android developers による「Hello Views」チュートリアルで紹介されているウィジットには次のようなものがあります。 Date Picker Time Picker Form Stuff Ｌ Custom Button Ｌ Edit Text Ｌ Checkbox Ｌ Radio Buttons Ｌ Toggle Button Ｌ Rating Bar Spinner Auto Complete Gallery 「Form Stuff」チュートリアルを日本語への翻訳と内容を補足しながらみていきます。今回はRadio Buttonsについてみていきます。 Radio Buttons Radio Buttonsの説明についてみていきます。 In this section, you will create two mutually-exclusive radio buttons (enabling one disables the other), using the RadioGroup and RadioButton widgets. When [...]]]></description>
			<content:encoded><![CDATA[<p><a href="http://developer.android.com/intl/ja/resources/tutorials/views/index.html" target="_blank">Android developers</a> による「Hello Views」チュートリアルで紹介されているウィジットには次のようなものがあります。</p>
<div style="border: 1px solid #c0c0c0; padding: 10px; margin-top: 20px;">
<ol>
<li>Date Picker</li>
<li>Time Picker</li>
<li>Form Stuff<br />
<span style="padding-left: 10px;">Ｌ Custom Button</span><br />
<span style="padding-left: 10px;">Ｌ Edit Text</span><br />
<span style="padding-left: 10px;">Ｌ Checkbox</span><br />
<span style="padding-left: 10px;">Ｌ <span style="color: #ff0000;">Radio Buttons</span></span><br />
<span style="padding-left: 10px;">Ｌ Toggle Button</span><br />
<span style="padding-left: 10px;">Ｌ Rating Bar</span></li>
<li>Spinner</li>
<li>Auto Complete</li>
<li>Gallery</li>
</ol>
</div>
<p>「<a href="http://developer.android.com/intl/ja/resources/tutorials/views/hello-formstuff.html" target="_blank">Form Stuff</a>」チュートリアルを日本語への翻訳と内容を補足しながらみていきます。今回はRadio Buttonsについてみていきます。</p>
<h2 style="padding-top: 40px; margin-bottom: 20px; padding-bottom: 0px;"><span style="color: #0000ff;">Radio Buttons</span></h2>
<p>Radio Buttonsの説明についてみていきます。</p>
<div style="border: 1px solid #c0c0c0; padding: 10px; margin-top: 20px;">In this section, you will create two mutually-exclusive radio buttons (enabling one disables the other), using the <code><a href="http://developer.android.com/reference/android/widget/RadioGroup.html" target="_blank">RadioGroup</a></code> and <code><a href="http://developer.android.com/reference/android/widget/RadioButton.html" target="_blank">RadioButton</a></code> widgets. When either radio button is pressed, a toast message will be displayed.</div>
<p>[訳]<br />
このセクションでは、<code><a href="http://developer.android.com/reference/android/widget/RadioGroup.html" target="_blank">RadioGroup</a></code>と<code><a href="http://developer.android.com/reference/android/widget/RadioButton.html" target="_blank">RadioButton</a></code>のウィジットを使って２つの相互に排他的なラジオボタン（１つが可能ならば他方が無効）を作ります。どちらかのラジオボタンが押されたときに、トーストメッセージを表示します。</p>
<p><span id="more-2194"></span></p>
<div class="title-blue-line-middle" style="margin-top: 50px;">プロジェクト</div>
<p>AndroidチュートリアルではCustom Button、Edit Text、Checkbox、<span style="color: #ff0000;">Radio Buttons</span>、Toggle Button、Rating Barは1つのプロジェクト内で説明していますが、このブログでは各フォーム要素ごとにプロジェクトを作成します。</p>
<p>FormStuffRadioButtonsという名前の新規プロジェクトを作成します。</p>
<ul style="margin-left: 20px;">
<li>プロジェクト名（Project name）<br />
<span style="color: #0000ff;">FormStuffRadioButtons</span></li>
<li>内容(Contents)<br />
<span style="color: #0000ff;">ワークスペース内に新規プロジェクトを作成</span></li>
<li>ビルド・ターゲット(Build Target)<br />
<span style="color: #0000ff;">Android 1.6</span></li>
<li>アプリケーション名（Application Name）<br />
<span style="color: #0000ff;">FormStuffRadioButtons</span></li>
<li>パッケージ名（Package Name）<br />
<span style="color: #0000ff;">localhost.helloview</span></li>
<li>アクティビティの作成（Create Activity）<br />
<span style="color: #0000ff;">FormStuffRadioButtons</span></li>
<li>最小 SDKバージョン（Min SDK Version）<br />
<span style="color: #0000ff;">4</span></li>
</ul>
<p>プロジェクト作成については「<a href="http://memories.zal.jp/WP/20110508_2056.html" target="_blank">新規 Android プロジェクトを作成する</a>」の記事に詳しく書いたので参考にしてください。パッケージ名については公開するつもりもないので、とりあえずローカル環境用という意味合いで「localhost」にしました。</p>
<div class="title-blue-line-middle" style="margin-top: 50px;">レイアウトファイルの作成(main.xml)</div>
<div style="border: 1px solid #c0c0c0; padding: 10px; margin-top: 20px;">Open the <span style="color: #008000;"><code>res/layout/main.xml</code></span> file and add two <code><a href="http://developer.android.com/reference/android/widget/RadioButton.html" target="_blank">RadioButton</a></code>s, nested in a <code><a href="http://developer.android.com/reference/android/widget/RadioGroup.html" target="_blank">RadioGroup</a></code> (inside the <code><a href="http://developer.android.com/reference/android/widget/LinearLayout.html" target="_blank">LinearLayout</a></code>):</div>
<p>[訳]<br />
<span style="color: #008000;"> <code>res/layout/main.xml</code></span>ファイルを開き、<code><a href="http://developer.android.com/reference/android/widget/RadioGroup.html" target="_blank">RadioGroup</a></code>でネストされた２つの<code><a href="http://developer.android.com/reference/android/widget/RadioButton.html" target="_blank">RadioButton</a></code>s要素を追加します（<code><a href="http://developer.android.com/reference/android/widget/LinearLayout.html" target="_blank">LinearLayout</a></code>の中に）。</p>
<pre class="brush: java;">&lt;?xml version="1.0" encoding="utf-8"?&gt;
&lt;LinearLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    &gt;
    &lt;RadioGroup
      android:layout_width="fill_parent"
      android:layout_height="wrap_content"
      android:orientation="vertical"&gt;
      &lt;RadioButton android:id="@+id/radio_red"
          android:layout_width="wrap_content"
          android:layout_height="wrap_content"
          android:text="Red" /&gt;
      &lt;RadioButton android:id="@+id/radio_blue"
          android:layout_width="wrap_content"
          android:layout_height="wrap_content"
          android:text="Blue" /&gt;
    &lt;/RadioGroup&gt;
&lt;/LinearLayout&gt;</pre>
<p style="margin-bottom: 30px;">※チュートリアルではエレメントの追加部分だけ記載されていましたが、この記事ではres/layout/main.xml の全コードを記載しておきます。</p>
<div style="border: 1px solid #c0c0c0; padding: 10px; margin-top: 50px;">It's important that the <code><a href="http://developer.android.com/reference/android/widget/RadioButton.html" target="_blank">RadioButton</a></code>s are grouped together by the <code><a href="http://developer.android.com/reference/android/widget/RadioGroup.html" target="_blank">RadioGroup</a></code> element so that no more than one can be selected at a time. This logic is automatically handled by the Android system. When one <code><a href="http://developer.android.com/reference/android/widget/RadioButton.html" target="_blank">RadioButton</a></code> within a group is selected, all others are automatically deselected.</div>
<p>[訳]<br />
<code><a href="http://developer.android.com/reference/android/widget/RadioButton.html" target="_blank">RadioButton</a></code>sは<code><a href="http://developer.android.com/reference/android/widget/RadioGroup.html" target="_blank">RadioGroup</a></code>要素によって一緒にグループ化されているということが重要です。そうすることにより同時に１つ以上は選択できなくなります。このロジックは自動的にAndroidシステムによってハンドルされます。１つのグループ内で１つの<code><a href="http://developer.android.com/reference/android/widget/RadioButton.html" target="_blank">RadioButton</a></code>が選択されると、他の全てのラジオボタンは自動的に非選択状態になります。</p>
<div class="title-blue-line-middle" style="margin-top: 50px;">アクティビティ作成(FormStuffRadioButtons.java)</div>
<pre class="brush: java;">package localhost.helloview;

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

public class FormStuffRadioButtons extends Activity {
    /** アクティビティが最初に作成されたときに呼ばれます */

	/** ラジオボタンがクリックされたときのリスナー */
    private OnClickListener radio_listener
                       = new OnClickListener() {
        public void onClick(View v) {
            // クリックされたときに実行されるアクション
            RadioButton rb = (RadioButton) v;
            Toast.makeText(
            	FormStuffRadioButtons.this,
            	rb.getText(),
            	Toast.LENGTH_SHORT).show();
        }
    };

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

        /** レイアウトからRadioButtonインスタンス生成 */
        final RadioButton radio_red
           = (RadioButton) findViewById(R.id.radio_red);
        final RadioButton radio_blue
           = (RadioButton) findViewById(R.id.radio_blue);
        /** RadioButtonインスタンスにリスナー追加 */
        radio_red.setOnClickListener(radio_listener);
        radio_blue.setOnClickListener(radio_listener);
    }
}</pre>
<p style="margin-bottom: 30px;">※チュートリアルでは追加部分だけ記載されていましたが、この記事ではFormStuffRadioButtons.java の全コードを記載しておきます。</p>
<div style="margin-top: 30px;">【13～24行目】</div>
<div style="border: 1px solid #c0c0c0; padding: 10px; margin-top: 10px;">
<p>To do something when each <code><a href="http://developer.android.com/reference/android/widget/RadioButton.html" target="_blank">RadioButton</a></code> is selected, you need an <code><a href="http://developer.android.com/reference/android/view/View.OnClickListener.html" target="_blank">View.OnClickListener</a></code>. In this case, you want the listener to be re-usable, so add the following code to create a new member in the <span style="color: #008000;">FormStuffRadioButtons</span> Activity:</p>
<p>First, the <code><a href="http://developer.android.com/reference/android/view/View.html" target="_blank">View</a></code> that is passed to the <code><a href="http://developer.android.com/reference/android/view/View.OnClickListener.html#onClick%28android.view.View%29" target="_blank">onClick(View)</a></code> method is cast into a RadioButton. Then a <code><a href="http://developer.android.com/reference/android/widget/Toast.html" target="_blank">Toast</a></code> message displays the selected radio button's text.</p>
</div>
<p>[訳]<br />
それぞれの<code><a href="http://developer.android.com/reference/android/widget/RadioButton.html" target="_blank">RadioButton</a></code>が選択されたときに何らかの処理をさせるためには、<code><a href="http://developer.android.com/reference/android/view/View.OnClickListener.html" target="_blank">View.OnClickListener</a></code>が必要です。このケースではリスナーを再利用したいので、次のコード(※このブログでは上記の3～24行目）を追加し<span style="color: #008000;">FormStuffRadioButtons</span>アクティビティに新しいメンバを作ります。</p>
<p>最初に<code><a href="http://developer.android.com/reference/android/view/View.OnClickListener.html#onClick%28android.view.View%29" target="_blank">onClick(View)</a></code>メソッドのパラメータとして渡された<code><a href="http://developer.android.com/reference/android/view/View.html" target="_blank">View</a></code>をRadioButtonにキャストします。それから選択されたラジオボタンのテキストが<code><a href="http://developer.android.com/reference/android/widget/Toast.html" target="_blank">Toast</a></code>メッセージで表示されます。</p>
<div style="margin-top: 50px;">【31～38行目】</div>
<div style="border: 1px solid #c0c0c0; padding: 10px; margin-top: 10px;">
<p>Now, at the bottom of the <code><a href="http://developer.android.com/reference/android/app/Activity.html#onCreate%28android.os.Bundle%29" target="_blank">onCreate()</a></code> method, add the following:</p>
<p>This captures each of the <code><a href="http://developer.android.com/reference/android/widget/RadioButton.html" target="_blank">RadioButton</a></code>s from the layout and adds the newly-created <code><a href="http://developer.android.com/reference/android/view/View.OnClickListener.html" target="_blank">View.OnClickListener</a></code> to each.</p>
</div>
<p>[訳]<br />
では、onCreateメソッドの下に次のコード(※このブログでは上記31～38行目)を追加します。</p>
<p>ここではレイアウトからそれぞれのRadioButtonsを取得し、それぞれに対して新たに作られたView.OnClickListenerを追加します。</p>
<div style="margin-top: 30px;">【補足】</div>
<ul>
<li>15行目で<code><a href="http://developer.android.com/reference/android/view/View.OnClickListener.html" target="_blank">OnClickListener</a></code><code>のインスタンスを生成しています。</code><code><a href="http://developer.android.com/reference/android/view/View.OnClickListener.html" target="_blank">OnClickListener</a></code>はインターフェースなので実装する場合は<code><a href="http://developer.android.com/reference/android/view/View.OnClickListener.html#onClick%28android.view.View%29" target="_blank">onClick</a></code>メソッドをオーバーライドしなければなりません。<br />
<span style="color: #888888; font-size: 10px;">※参考：<a href="http://developer.android.com/reference/android/view/View.OnClickListener.html" target="_blank">android.view.OnClickListener</a></span></li>
<li>16行目でonClickメソッドをオーバーライドしています。onClickメソッドはViewがクリックされたときに呼ばれます。パラメータとして渡されるのはクリックされたViewインスタンスです。</li>
<li>19～22行目でラジオボタンがクリックされたときの処理が書かれています。それぞれに応じたメッセージがトーストで表示されます。</li>
<li>31～35ではそれぞれのラジオボタンのインスタンスを生成しています。findViewByIdメソッドは対応するIDのレイアウトの要素からViewクラス型のインスタンスを生成し返します。Viewクラス型で返すのでRadioButtonクラス型にキャストし代入します。</li>
<li>37～38行目では各インスタンスにリスナーを追加しています。</li>
</ul>
<div class="title-blue-line-middle" style="margin-top: 50px;">AVDによる実行</div>
<p>AVDによるアプリケーションの実行については「<a href="http://memories.zal.jp/WP/20110516_2073.html#app_excute" target="_blank">AVDでアプリケーションを実行する</a>」の記事で詳しく書きました。参考にしてください。</p>
<p>実行結果をみてみます。次のような画面が表示されました。</p>
<p><img class="aligncenter size-full wp-image-2195" title="android125" src="http://memories.zal.jp/WP/wp-content/uploads/2011/12/android125.jpg" alt="" width="500" height="460" /></p>
]]></content:encoded>
			<wfw:commentRss>http://memories.zal.jp/WP/blog/20111218_2194.html/feed</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>チェックボックス/Form Stuff について</title>
		<link>http://memories.zal.jp/WP/blog/20111205_2189.html</link>
		<comments>http://memories.zal.jp/WP/blog/20111205_2189.html#comments</comments>
		<pubDate>Sun, 04 Dec 2011 15:36:08 +0000</pubDate>
		<dc:creator>admin</dc:creator>
				<category><![CDATA[Android]]></category>
		<category><![CDATA[Hello_Views]]></category>

		<guid isPermaLink="false">http://memories.zal.jp/WP/?p=2189</guid>
		<description><![CDATA[Android developers による「Hello Views」チュートリアルで紹介されているウィジットには次のようなものがあります。 Date Picker Time Picker Form Stuff Ｌ Custom Button Ｌ Edit Text Ｌ Checkbox Ｌ Radio Buttons Ｌ Toggle Button Ｌ Rating Bar Spinner Auto Complete Gallery 「Form Stuff」チュートリアルを日本語への翻訳と内容を補足しながらみていきます。今回はCheckboxについてみていきます。 CheckBox CheckBoxの説明についてみていきます。 In this section, you will create a checkbox for selecting items, using the CheckBox widget. When the checkbox is pressed, a toast message will indicate [...]]]></description>
			<content:encoded><![CDATA[<p><a href="http://developer.android.com/intl/ja/resources/tutorials/views/index.html" target="_blank">Android developers</a> による「Hello Views」チュートリアルで紹介されているウィジットには次のようなものがあります。</p>
<div style="border: 1px solid #c0c0c0; padding: 10px; margin-top: 20px;">
<ol>
<li>Date Picker</li>
<li>Time Picker</li>
<li>Form Stuff<br />
<span style="padding-left: 10px;">Ｌ Custom Button</span><br />
<span style="padding-left: 10px;">Ｌ Edit Text</span><br />
<span style="padding-left: 10px;">Ｌ <span style="color: #ff0000;">Checkbox</span></span><br />
<span style="padding-left: 10px;">Ｌ Radio Buttons</span><br />
<span style="padding-left: 10px;">Ｌ Toggle Button</span><br />
<span style="padding-left: 10px;">Ｌ Rating Bar</span></li>
<li>Spinner</li>
<li>Auto Complete</li>
<li>Gallery</li>
</ol>
</div>
<p>「<a href="http://developer.android.com/intl/ja/resources/tutorials/views/hello-formstuff.html" target="_blank">Form Stuff</a>」チュートリアルを日本語への翻訳と内容を補足しながらみていきます。今回はCheckboxについてみていきます。</p>
<h2 style="padding-top: 40px; margin-bottom: 20px; padding-bottom: 0px;"><span style="color: #0000ff;">CheckBox</span></h2>
<p>CheckBoxの説明についてみていきます。</p>
<div style="border: 1px solid #c0c0c0; padding: 10px; margin-top: 20px;">In this section, you will create a checkbox for selecting items, using the <code><a href="http://developer.android.com/reference/android/widget/CheckBox.html" target="_blank">CheckBox</a></code> widget. When the checkbox is pressed, a toast message will indicate the current state of the checkbox.</div>
<p>[訳]<br />
このセクションでは、<code><a href="http://developer.android.com/reference/android/widget/CheckBox.html" target="_blank">CheckBox</a></code> ウィジットを使ってユーザが選択できるチェックボックスを作ります。チェックボックスが押されたときに、チェックボックスの現在の状態を示すトーストメッセージが表示されます。</p>
<div class="title-blue-line-middle" style="margin-top: 50px;">プロジェクト</div>
<p>AndroidチュートリアルではCustom Button、Edit Text、<span style="color: #ff0000;">Checkbox</span>、Radio Buttons、Toggle Button、Rating Barは1つのプロジェクト内で説明していますが、このブログでは各フォーム要素ごとにプロジェクトを作成します。</p>
<p>FormStuffCheckBoxという名前の新規プロジェクトを作成します。</p>
<ul style="margin-left: 20px;">
<li>プロジェクト名（Project name）<br />
<span style="color: #0000ff;">FormStuffCheckBox</span></li>
<li>内容(Contents)<br />
<span style="color: #0000ff;">ワークスペース内に新規プロジェクトを作成</span></li>
<li>ビルド・ターゲット(Build Target)<br />
<span style="color: #0000ff;">Android 1.6</span></li>
<li>アプリケーション名（Application Name）<br />
<span style="color: #0000ff;">FormStuffCheckBox</span></li>
<li>パッケージ名（Package Name）<br />
<span style="color: #0000ff;">localhost.helloview</span></li>
<li>アクティビティの作成（Create Activity）<br />
<span style="color: #0000ff;">FormStuffCheckBox</span></li>
<li>最小 SDKバージョン（Min SDK Version）<br />
<span style="color: #0000ff;">4</span></li>
</ul>
<p>プロジェクト作成については「<a href="http://memories.zal.jp/WP/20110508_2056.html" target="_blank">新規 Android プロジェクトを作成する</a>」の記事に詳しく書いたので参考にしてください。パッケージ名については公開するつもりもないので、とりあえずローカル環境用という意味合いで「localhost」にしました。</p>
<div class="title-blue-line-middle" style="margin-top: 50px;">レイアウトファイルの作成(main.xml)</div>
<div style="border: 1px solid #c0c0c0; padding: 10px; margin-top: 20px;">Open the <span style="color: #339966;"><code>res/layout/main.xml</code></span> file and add the <code><a href="http://developer.android.com/reference/android/widget/CheckBox.html" target="_blank">CheckBox</a></code> element (inside the <code><a href="http://developer.android.com/reference/android/widget/LinearLayout.html" target="_blank">LinearLayout</a></code>):</div>
<p>[訳]<br />
<span style="color: #339966;">res/layout/main.xml</span> ファイルを開き、<code><a href="http://developer.android.com/reference/android/widget/CheckBox.html" target="_blank">CheckBox</a></code>要素を追加します（<code><a href="http://developer.android.com/reference/android/widget/LinearLayout.html" target="_blank">LinearLayout</a></code>の中に）。</p>
<pre class="brush: java;">&lt;?xml version="1.0" encoding="utf-8"?&gt;
&lt;LinearLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    &gt;
    &lt;CheckBox android:id="@+id/checkbox"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="check it out" /&gt;
&lt;/LinearLayout&gt;</pre>
<p style="margin-bottom: 30px;">※チュートリアルではエレメントの追加部分だけ記載されていましたが、この記事ではres/layout/main.xml の全コードを記載しておきます。</p>
<div class="title-blue-line-middle" style="margin-top: 50px;">アクティビティ作成(FormStuffCheckBox.java)</div>
<div style="border: 1px solid #c0c0c0; padding: 10px; margin-top: 20px;">To do something when the state is changed, add the following code to the end of the <code><a href="http://developer.android.com/reference/android/app/Activity.html#onCreate%28android.os.Bundle%29" target="_blank">onCreate()</a></code> method:</div>
<p>[訳]<br />
状態が変化したときに何らかの処理をするため、次のコードを<code><a href="http://developer.android.com/reference/android/app/Activity.html#onCreate%28android.os.Bundle%29" target="_blank">onCreate()</a></code>メソッドの後ろに追加します。</p>
<pre class="brush: java;">package localhost.helloview;

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

public class FormStuffCheckBox extends Activity {
	/** アクティビティが最初に作られた時に呼ばれます */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);

        //レイアウトからCheckBoxインスタンス生成
        final CheckBox checkbox
             = (CheckBox) findViewById(R.id.checkbox);
        //クリックイベントハンドラを付与
        checkbox.setOnClickListener(new OnClickListener() {
            public void onClick(View v) {
                //チェックされている場合
                if (((CheckBox) v).isChecked()) {
                    Toast.makeText(
                    	FormStuffCheckBox.this,
                    	"Selected",
                    	Toast.LENGTH_SHORT).show();
                //チェックされていない場合
                }else{
                    Toast.makeText(
                    	FormStuffCheckBox.this,
                    	"Not selected",
                    	Toast.LENGTH_SHORT).show();
                }
            }
        });
    }
}</pre>
<p style="margin-bottom: 30px;">※チュートリアルでは追加部分だけ記載されていましたが、この記事ではFormStuffCheckBox.java の全コードを記載しておきます。</p>
<div style="border: 1px solid #c0c0c0; padding: 10px; margin-top: 20px;">This captures the <code><a href="http://developer.android.com/reference/android/widget/CheckBox.html" target="_blank">CheckBox</a></code> element from the layout, then adds an <code><a href="http://developer.android.com/reference/android/view/View.OnClickListener.html" target="_blank">View.OnClickListener</a></code>. The <code><a href="http://developer.android.com/reference/android/view/View.OnClickListener.html" target="_blank">View.OnClickListener</a></code> must implement the <code><a href="http://developer.android.com/reference/android/view/View.OnClickListener.html#onClick%28android.view.View%29" target="_blank">onClick(View)</a></code> callback method, which defines the action to be made when the checkbox is clicked. When clicked, <code><a href="http://developer.android.com/reference/android/widget/CompoundButton.html#isChecked%28%29" target="_blank">isChecked()</a></code> is called to check the new state of the check box. If it has been checked, then a <code><a href="http://developer.android.com/reference/android/widget/Toast.html" target="_blank">Toast</a></code> displays the message "Selected", otherwise it displays "Not selected". Note that the <code><a href="http://developer.android.com/reference/android/view/View.html" target="_blank">View</a></code> object that is passed in the <code><a href="http://developer.android.com/reference/android/view/View.OnClickListener.html#onClick%28android.view.View%29" target="_blank">onClick(View)</a></code> callback must be cast to a <code><a href="http://developer.android.com/reference/android/widget/CheckBox.html" target="_blank">CheckBox</a></code> because the <code><a href="http://developer.android.com/reference/android/widget/CompoundButton.html#isChecked%28%29" target="_blank">isChecked()</a></code> method is not defined by the parent <code><a href="http://developer.android.com/reference/android/view/View.html" target="_blank">View</a></code> class. The <code><a href="http://developer.android.com/reference/android/widget/CheckBox.html" target="_blank">CheckBox</a></code> handles its own state changes, so you only need to query the current state.</div>
<p>[訳]<br />
ここではレイアウトから<code><a href="http://developer.android.com/reference/android/widget/CheckBox.html" target="_blank">CheckBox</a></code> エレメントを取得し、<code><a href="http://developer.android.com/reference/android/view/View.OnClickListener.html" target="_blank">View.OnClickListener</a></code>を付与します。OnClickListenerは<code><a href="http://developer.android.com/reference/android/view/View.OnClickListener.html#onClick%28android.view.View%29" target="_blank">onClick(View)</a></code>コールバックメソッドを実装しなければなりません。onClickメソッドにはチェックボックスがクリックされたときに処理されるアクションを定義します。クリックしたときに、新しいチェックの状態をチェックするため<code><a href="http://developer.android.com/reference/android/widget/CompoundButton.html#isChecked%28%29" target="_blank">isChecked()</a></code>メソッドが呼ばれます。もしチェックされている状態ならばトーストには"Selected"というメッセージが表示され、そうでなければ"Not selected"と表示されます。<code><a href="http://developer.android.com/reference/android/view/View.OnClickListener.html#onClick%28android.view.View%29" target="_blank">onClick(View)</a></code>コールバックで渡される<code><a href="http://developer.android.com/reference/android/view/View.html" target="_blank">View</a></code>オブジェクトは<code><a href="http://developer.android.com/reference/android/widget/CheckBox.html" target="_blank">CheckBox</a></code>にキャストしなければなりません。なぜなら<code><a href="http://developer.android.com/reference/android/widget/CompoundButton.html#isChecked%28%29" target="_blank">isChecked()</a></code>は親の<code><a href="http://developer.android.com/reference/android/view/View.html" target="_blank">View</a></code>クラスには定義されていないからです。CheckBoxは自分自身の状態変化をハンドルします。なので現在の状態を尋ねるだけでよくなります。</p>
<div style="margin-top: 30px;">[補足]</div>
<ul>
<li>18行目でレイアウトのIDがcheckboxの要素から<code><a href="http://developer.android.com/reference/android/widget/CheckBox.html" target="_blank">CheckBox</a></code>インスタンスを生成します。</li>
<li>21行目で<code><a href="http://developer.android.com/reference/android/widget/CheckBox.html" target="_blank">CheckBox</a></code>インスタンスにを<code><a href="http://developer.android.com/reference/android/view/View.OnClickListener.html" target="_blank">View.OnClickListener</a></code>を付与しています。<code><a href="http://developer.android.com/reference/android/view/View.OnClickListener.html" target="_blank">OnClickListener</a></code>はインターフェースなので実装する場合は<code><a href="http://developer.android.com/reference/android/view/View.OnClickListener.html#onClick%28android.view.View%29" target="_blank">onClick</a></code>メソッドをオーバーライドしなければなりません。<br />
<span style="color: #888888; font-size: 10px;">※参考：<a href="http://developer.android.com/reference/android/view/View.OnClickListener.html" target="_blank">android.view.OnClickListener</a></span></li>
<li>22行目でonClickメソッドをオーバーライドしています。onClickメソッドはViewがクリックされたときに呼ばれます。パラメータとして渡されるのはクリックされたViewインスタンスです。</li>
<li>24行目でチェックボックスがチェック状態であるか判定しています。パラメータとして渡されたvはViewクラス型なのでisCheckedメソッドは定義されていません。そこでメソッドが定義されているCheckBoxクラス型にキャストします。CheckBoxクラスの<a href="http://developer.android.com/reference/android/widget/CheckBox.html" target="_blank">リファレンス</a>をみるとこのクラス自体が定義しているわけではないようです。ViewからChecBoxまでには次のようなクラス階層があります。
<pre>      android.view.View
        Ｌ android.widget.TextView
            Ｌ android.widget.Button
                Ｌ <span style="color: #ff0000;">android.widget.CompoundButton</span>
                    Ｌ 	android.widget.CheckBox</pre>
<p>　CheckBoxのスーパークラスであるCompoundButtonクラスで実装されおり、それを継承してます。</li>
<li>23～28行目がチェックボックスがチェックされたときの処理が、29行目から35行目はチェックが外れたときの処理が書かれています。それぞれに応じたメッセージがトーストで表示されます。</li>
</ul>
<div class="title-blue-line-middle" style="margin-top: 50px;">AVDによる実行</div>
<p>AVDによるアプリケーションの実行については「<a href="http://memories.zal.jp/WP/20110516_2073.html#app_excute" target="_blank">AVDでアプリケーションを実行する</a>」の記事で詳しく書きました。参考にしてください。</p>
<p>実行結果をみてみます。次のような画面が表示されました。</p>
<p><img class="aligncenter size-full wp-image-2190" title="android124" src="http://memories.zal.jp/WP/wp-content/uploads/2011/12/android124.jpg" alt="" width="500" height="462" /></p>
]]></content:encoded>
			<wfw:commentRss>http://memories.zal.jp/WP/blog/20111205_2189.html/feed</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>編集テキスト（入力ボックス）/Form Stuff について</title>
		<link>http://memories.zal.jp/WP/blog/20111122_2185.html</link>
		<comments>http://memories.zal.jp/WP/blog/20111122_2185.html#comments</comments>
		<pubDate>Tue, 22 Nov 2011 07:18:32 +0000</pubDate>
		<dc:creator>admin</dc:creator>
				<category><![CDATA[Android]]></category>
		<category><![CDATA[Hello_Views]]></category>

		<guid isPermaLink="false">http://memories.zal.jp/WP/?p=2185</guid>
		<description><![CDATA[Android developers による「Hello Views」チュートリアルで紹介されているウィジットには次のようなものがあります。 Date Picker Time Picker Form Stuff Ｌ Custom Button Ｌ Edit Text Ｌ Checkbox Ｌ Radio Buttons Ｌ Toggle Button Ｌ Rating Bar Spinner Auto Complete Gallery 「Form Stuff」チュートリアルを日本語への翻訳と内容を補足しながらみていきます。今回はForm Stuffの編集テキスト（入力ボックス）についてみていきます。 Edit Text(編集テキスト) Edit Textの説明についてみていきます。 In this section, you will create a text field for user input, using the EditText widget. Once text has been entered into [...]]]></description>
			<content:encoded><![CDATA[<p><a href="http://developer.android.com/intl/ja/resources/tutorials/views/index.html" target="_blank">Android developers</a> による「Hello Views」チュートリアルで紹介されているウィジットには次のようなものがあります。</p>
<div style="border: 1px solid #c0c0c0; padding: 10px; margin-top: 20px;">
<ol>
<li>Date Picker</li>
<li>Time Picker</li>
<li>Form Stuff<br />
<span style="padding-left: 10px;">Ｌ Custom Button</span><br />
<span style="padding-left: 10px;">Ｌ <span style="color: #ff0000;">Edit Text</span></span><br />
<span style="padding-left: 10px;">Ｌ Checkbox</span><br />
<span style="padding-left: 10px;">Ｌ Radio Buttons</span><br />
<span style="padding-left: 10px;">Ｌ Toggle Button</span><br />
<span style="padding-left: 10px;">Ｌ Rating Bar</span></li>
<li>Spinner</li>
<li>Auto Complete</li>
<li>Gallery</li>
</ol>
</div>
<p>「<a href="http://developer.android.com/intl/ja/resources/tutorials/views/hello-formstuff.html" target="_blank">Form Stuff</a>」チュートリアルを日本語への翻訳と内容を補足しながらみていきます。今回はForm Stuffの編集テキスト（入力ボックス）についてみていきます。</p>
<h2 style="padding-top: 40px; margin-bottom: 20px; padding-bottom: 0px;"><span style="color: #0000ff;">Edit Text(編集テキスト)</span></h2>
<p>Edit Textの説明についてみていきます。</p>
<div style="border: 1px solid #c0c0c0; padding: 10px; margin-top: 20px;">In this section, you will create a text field for user input, using the <code><a href="http://developer.android.com/reference/android/widget/EditText.html" target="_blank">EditText</a></code> widget. Once text has been entered into the field, the "Enter" key will display the text in a toast message.</div>
<p>[訳]<br />
このセクションでは、<code><a href="http://developer.android.com/reference/android/widget/EditText.html" target="_blank">EditText</a></code> ウィジットを使ってユーザが入力できるテキストフィールドを作ります。一度そのフィールドにテキストを入力し、"Enter"キーを押せばトーストメッセージでそのテキストが表示されます。</p>
<p><span id="more-2185"></span></p>
<div class="title-blue-line-middle" style="margin-top: 50px;">プロジェクト</div>
<p>AndroidチュートリアルではCustom Button、<span style="color: #ff0000;">Edit Text</span>、Checkbox、Radio Buttons、Toggle Button、Rating Barは1つのプロジェクト内で説明していますが、このブログでは各フォーム要素ごとにプロジェクトを作成します。</p>
<p>FormStuffEditText という名前の新規プロジェクトを作成します。</p>
<ul style="margin-left: 20px;">
<li>プロジェクト名（Project name）<br />
<span style="color: #0000ff;">FormStuffEditText</span></li>
<li>内容(Contents)<br />
<span style="color: #0000ff;">ワークスペース内に新規プロジェクトを作成</span></li>
<li>ビルド・ターゲット(Build Target)<br />
<span style="color: #0000ff;">Android 1.6</span></li>
<li>アプリケーション名（Application Name）<br />
<span style="color: #0000ff;">FormStuffEditText</span></li>
<li>パッケージ名（Package Name）<br />
<span style="color: #0000ff;">localhost.helloview</span></li>
<li>アクティビティの作成（Create Activity）<br />
<span style="color: #0000ff;">FormStuffEditText</span></li>
<li>最小 SDKバージョン（Min SDK Version）<br />
<span style="color: #0000ff;">4</span></li>
</ul>
<p>プロジェクト作成については「<a href="http://memories.zal.jp/WP/20110508_2056.html" target="_blank">新規 Android プロジェクトを作成する</a>」の記事に詳しく書いたので参考にしてください。パッケージ名については公開するつもりもないので、とりあえずローカル環境用という意味合いで「localhost」にしました。</p>
<div class="title-blue-line-middle" style="margin-top: 50px;">レイアウトファイルの作成(main.xml)</div>
<div style="border: 1px solid #c0c0c0; padding: 10px; margin-top: 20px;">Open the <span style="color: #008000;">res/layout/main.xml </span>file and add the <code><a href="http://developer.android.com/reference/android/widget/EditText.html" target="_blank">EditText</a></code> (inside the <code><a href="http://developer.android.com/reference/android/widget/LinearLayout.html" target="_blank">LinearLayout</a></code>)：</div>
<p>[訳]</p>
<p><span style="color: #008000;">res/layout/main.xml</span> ファイルを開き、<code><a href="http://developer.android.com/reference/android/widget/EditText.html" target="_blank">EditText</a></code>を追加します（<code><a href="http://developer.android.com/reference/android/widget/LinearLayout.html" target="_blank">LinearLayout</a>の中に</code>）。</p>
<pre class="brush: java;">&lt;?xml version="1.0" encoding="utf-8"?&gt;
&lt;LinearLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    &gt;
    &lt;EditText
        android:id="@+id/edittext"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"/&gt;
&lt;/LinearLayout&gt;</pre>
<p style="margin-bottom: 30px;">※チュートリアルではエレメントの追加部分だけ記載されていましたが、この記事ではres/layout/main.xml の全コードを記載しておきます。</p>
<div class="title-blue-line-middle" style="margin-top: 50px;">アクティビティ作成(FormStuffEditText.java)</div>
<div style="border: 1px solid #c0c0c0; padding: 10px; margin-top: 20px;">To do something with the text that the user types, add the following code to the end of the <code><a href="http://developer.android.com/reference/android/app/Activity.html#onCreate%28android.os.Bundle%29" target="_blank">onCreate()</a></code> method:</div>
<p>[訳]<br />
ユーザがタイプするテキストに何か動作させる為には、<code><a href="http://developer.android.com/reference/android/app/Activity.html#onCreate%28android.os.Bundle%29" target="_blank">onCreate()</a></code>メソッドの後ろに次のコードを追加します。</p>
<pre class="brush: java;">package localhost.helloview;

import android.app.Activity;
import android.os.Bundle;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnKeyListener;
import android.widget.EditText;
import android.widget.Toast;

public class FormStuffEditText extends Activity {
    /** アクティビティが最初に作られた時に呼ばれます */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        final EditText edittext
                     = (EditText) findViewById(R.id.edittext);
        edittext.setOnKeyListener(new OnKeyListener() {
            public boolean onKey(View v, int keyCode, KeyEvent event) {
                //イベントが"enter"キーでのkey-downイベントならば
                if ((event.getAction()==KeyEvent.ACTION_DOWN) &amp;&amp;
                    (keyCode==KeyEvent.KEYCODE_ENTER)) {
                  // キーが押された時に行うアクション
                  Toast.makeText(
                       FormStuffEditText.this
                      ,edittext.getText()
                      ,Toast.LENGTH_SHORT
                  ).show();
                  return true;
                }
                return false;
            }
        });
    }
}</pre>
<p style="margin-bottom: 30px;">※チュートリアルではリスナーの追加部分だけ記載されていましたが、この記事ではFormStuffEditText.java の全コードを記載しておきます。</p>
<div style="border: 1px solid #c0c0c0; padding: 10px; margin-top: 20px;">This captures the <code><a href="http://developer.android.com/reference/android/widget/EditText.html" target="_blank">EditText</a></code> element from the layout and adds an <code><a href="http://developer.android.com/reference/android/view/View.OnKeyListener.html" target="_blank">View.OnKeyListener</a></code>. The <code><a href="http://developer.android.com/reference/android/view/View.OnKeyListener.html" target="_blank">View.OnKeyListener</a></code> must implement the <code><a href="http://developer.android.com/reference/android/view/View.OnKeyListener.html#onKey%28android.view.View,%20int,%20android.view.KeyEvent%29" target="_blank">onKey(View, int, KeyEvent)</a></code> method, which defines the action to be made when a key is pressed while the widget has focus. In this case, the method is defined to listen for the Enter key (when pressed down), then pop up a <code><a href="http://developer.android.com/reference/android/widget/Toast.html" target="_blank">Toast</a></code> message with the text that has been entered. The <code><a href="http://developer.android.com/reference/android/view/View.OnKeyListener.html#onKey%28android.view.View,%20int,%20android.view.KeyEvent%29" target="_blank">onKey(View, int, KeyEvent)</a></code> method should always return <code>true</code> if the event has been handled, so that the event doesn't bubble-up (which would result in a carriage return in the text field).</div>
<p>[訳]<br />
ここではレイアウトから<code><a href="http://developer.android.com/reference/android/widget/EditText.html" target="_blank">EditText</a></code> エレメントを取得し、 <code><a href="http://developer.android.com/reference/android/view/View.OnKeyListener.html" target="_blank">View.OnKeyListener</a></code>を付与します。<code><a href="http://developer.android.com/reference/android/view/View.OnKeyListener.html" target="_blank">View.OnKeyListener</a></code>は<code><a href="http://developer.android.com/reference/android/view/View.OnKeyListener.html#onKey%28android.view.View,%20int,%20android.view.KeyEvent%29" target="_blank">onKey(View, int, KeyEvent)</a></code>メソッドを実装しなければなりません。onKeyメソッドにはウィジットがフォーカスされている間、キーが押されたときに処理されるアクションを定義します。このケースでは、メソッドにEnterキーからの応答（押されたとき）に対するアクションが定義されており、入力されているテキストを<code><a href="http://developer.android.com/reference/android/widget/Toast.html" target="_blank">Toast</a></code>メッセージでポップアップ表示します。<code><a href="http://developer.android.com/reference/android/view/View.OnKeyListener.html#onKey%28android.view.View,%20int,%20android.view.KeyEvent%29" target="_blank">onKey(View, int, KeyEvent)</a></code>メソッドはイベントがハンドルされたならば常にtrueを返すべきであり、そうすることによりイベントが他に伝達しなくなります（テキストフィールドでの改行コードの結果はそのようになります）。</p>
<p><img class="aligncenter size-full wp-image-2187" style="margin-top: 20px;" title="android121" src="http://memories.zal.jp/WP/wp-content/uploads/2011/11/android121.jpg" alt="" width="342" height="218" /></p>
<p style="margin-top: 10px;">[補足]</p>
<ul>
<li>17行目でレイアウトのIDがedittextの要素から<code><a href="http://developer.android.com/reference/android/widget/EditText.html" target="_blank">EditText</a></code>インスタンスを生成します。</li>
<li>19行目で<code><a href="http://developer.android.com/reference/android/widget/Button.html" target="_blank"></a></code><code><a href="http://developer.android.com/reference/android/widget/EditText.html" target="_blank">EditText</a></code>インスタンスに<code><a href="http://developer.android.com/reference/android/view/View.OnKeyListener.html" target="_blank">OnKeyListener</a></code>リスナーを付与しています。<code><a href="http://developer.android.com/reference/android/view/View.OnKeyListener.html" target="_blank">OnKeyListener</a></code>はインターフェースなので実装する場合は<code><a href="http://developer.android.com/reference/android/view/View.OnKeyListener.html#onKey%28android.view.View,%20int,%20android.view.KeyEvent%29" target="_blank">onKey</a></code>メソッドをオーバーライドしなければなりません。<br />
<span style="color: #888888; font-size: 10px;">※参考：<a href="http://developer.android.com/intl/ja/reference/android/view/View.OnKeyListener.html" target="_blank">android.view.View.OnKeyListener</a></span></li>
<li>20行目でonKeyメソッドをオーバーライドしています。</li>
<li>25～28行目では"Enter"キーが押されたときの処理が書かれており、このサンプルでは入力されたテキストが<code><a href="http://developer.android.com/reference/android/widget/Toast.html" target="_blank">Toast</a></code>メッセージで表示させます。</li>
</ul>
<p style="margin-top: 50px;">onKeyメソッドについて<a href="http://developer.android.com/intl/ja/reference/android/view/View.OnKeyListener.html#onKey%28android.view.View,%20int,%20android.view.KeyEvent%29" target="_blank">リファレンス</a>を詳しくみてみます。</p>
<div style="background-color: #b5b5b5; padding: 10px;">public abstract boolean onKey (View <span style="color: #000080;">v</span>, int <span style="color: #000080;">keyCode</span>, Key<span style="color: #000080;">Event event</span>)</div>
<div style="border: 1px solid #c0c0c0; padding: 10px; margin-top: 20px;">Called when a key is dispatched to a view. This allows listeners to  get a chance to respond before the target view.</div>
<p>[訳]<br />
キーからビューに処理実行権を割り当てるときに呼ばれます。このことはリスナーが対象となるビューより前に応答の変化を取得できることを可能にします。</p>
<div>
<h3>Parameters</h3>
<table>
<tbody>
<tr>
<td><span style="color: #000080;">v</span></td>
<td><span style="color: #999999;">The view the key has been dispatched to.</span><br />
キーから処理実行権を割り当てられるビュー</td>
</tr>
<tr>
<td><span style="color: #000080;">keyCode</span></td>
<td><span style="color: #999999;">The code for the physical key that was pressed</span><br />
押されたときの物理的キーのコード</td>
</tr>
<tr>
<td><span style="color: #000080;">event</span></td>
<td><span style="color: #999999;">The KeyEvent object containing full information about the event.</span><br />
イベントについての完全な情報を含むキーイベントオブジェクト</td>
</tr>
</tbody>
</table>
</div>
<div>
<h3>Returns</h3>
<p><span style="color: #888888;">True if the listener has consumed the event, false otherwise.</span><br />
リスナーがイベントを処理し終わっていればTrueを、そうでなければfalse</p>
</div>
<div class="title-blue-line-middle" style="margin-top: 50px;">AVDによる実行</div>
<p>AVDによるアプリケーションの実行については「<a href="http://memories.zal.jp/WP/20110516_2073.html#app_excute" target="_blank">AVDでアプリケーションを実行する</a>」の記事で詳しく書きました。参考にしてください。</p>
<p>実行結果をみてみます。次のような画面が表示されました。</p>
<p><img class="aligncenter size-full wp-image-2188" title="android122" src="http://memories.zal.jp/WP/wp-content/uploads/2011/11/android122.jpg" alt="" width="500" height="461" /></p>
]]></content:encoded>
			<wfw:commentRss>http://memories.zal.jp/WP/blog/20111122_2185.html/feed</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>カスタムボタン/Form Stuff について</title>
		<link>http://memories.zal.jp/WP/blog/20111115_2178.html</link>
		<comments>http://memories.zal.jp/WP/blog/20111115_2178.html#comments</comments>
		<pubDate>Tue, 15 Nov 2011 07:47:35 +0000</pubDate>
		<dc:creator>admin</dc:creator>
				<category><![CDATA[Android]]></category>
		<category><![CDATA[Hello_Views]]></category>

		<guid isPermaLink="false">http://memories.zal.jp/WP/?p=2178</guid>
		<description><![CDATA[Android developers による「Hello Views」チュートリアルで紹介されているウィジットには次のようなものがあります。 Date Picker Time Picker Form Stuff Ｌ Custom Button Ｌ Edit Text Ｌ Checkbox Ｌ Radio Buttons Ｌ Toggle Button Ｌ Rating Bar Spinner Auto Complete Gallery 今回から6回に分けて「Form Stuff」チュートリアルを日本語への翻訳と内容を補足しながらみていきます。今回はカスタムボタンについてみていきます。 Custom Button(カスタムボタン) Custom Buttonの説明についてみていきます。 In this section, you will create a button with a custom image instead of text, using the Button widget and an XML file that [...]]]></description>
			<content:encoded><![CDATA[<p><a href="http://developer.android.com/intl/ja/resources/tutorials/views/index.html" target="_blank">Android developers</a> による「Hello Views」チュートリアルで紹介されているウィジットには次のようなものがあります。</p>
<div style="border: 1px solid #c0c0c0; padding: 10px; margin-top: 20px;">
<ol>
<li>Date Picker</li>
<li>Time Picker</li>
<li>Form Stuff<br />
<span style="padding-left: 10px;">Ｌ <span style="color: #ff0000;">Custom Button</span></span><br />
<span style="padding-left: 10px;">Ｌ Edit Text</span><br />
<span style="padding-left: 10px;">Ｌ Checkbox</span><br />
<span style="padding-left: 10px;">Ｌ Radio Buttons</span><br />
<span style="padding-left: 10px;">Ｌ Toggle Button</span><br />
<span style="padding-left: 10px;">Ｌ Rating Bar</span></li>
<li>Spinner</li>
<li>Auto Complete</li>
<li>Gallery</li>
</ol>
</div>
<p>今回から6回に分けて「<a href="http://developer.android.com/intl/ja/resources/tutorials/views/hello-formstuff.html" target="_blank">Form Stuff</a>」チュートリアルを日本語への翻訳と内容を補足しながらみていきます。今回はカスタムボタンについてみていきます。</p>
<h2 style="padding-top: 40px; margin-bottom: 20px; padding-bottom: 0px;"><span style="color: #0000ff;">Custom Button(カスタムボタン)</span></h2>
<p>Custom Buttonの説明についてみていきます。</p>
<div style="border: 1px solid #c0c0c0; padding: 10px; margin-top: 20px;">In this section, you will create a button with a custom image instead of text, using the <code><a href="http://developer.android.com/reference/android/widget/Button.html" target="_blank">Button</a></code> widget and an XML file that defines three different images to use for the different button states. When the button is pressed, a short message will be displayed.</div>
<p>[訳]<br />
このセクションでは、テキストの代わりにカスタム画像を使ってボタンを作成します。カスタムボタンには<a href="http://developer.android.com/reference/android/widget/Button.html" target="_blank">Button</a>ウィジットとXMLファイルを使いますが、XMLでは異なったボタン状態に対応する異なった3つの画像を定義します。ボタンを押したときに短いメッセージを表示します。</p>
<p><span id="more-2178"></span></p>
<div class="title-blue-line-middle" style="margin-top: 50px;">プロジェクト</div>
<div style="border: 1px solid #c0c0c0; padding: 10px; margin-top: 20px;">Start a new project named HelloFormStuff.</div>
<p>[訳]<br />
HelloFormStuff という名前の新規プロジェクトを開始します。</p>
<ul style="margin-left: 20px;">
<li>プロジェクト名（Project name）<br />
<span style="color: #0000ff;">HelloFormStuff</span></li>
<li>内容(Contents)<br />
<span style="color: #0000ff;">ワークスペース内に新規プロジェクトを作成</span></li>
<li>ビルド・ターゲット(Build Target)<br />
<span style="color: #0000ff;">Android 1.6</span></li>
<li>アプリケーション名（Application Name）<br />
<span style="color: #0000ff;">HelloFormStuff</span></li>
<li>パッケージ名（Package Name）<br />
<span style="color: #0000ff;">localhost.helloview</span></li>
<li>アクティビティの作成（Create Activity）<br />
<span style="color: #0000ff;">HelloFormStuff</span></li>
<li>最小 SDKバージョン（Min SDK Version）<br />
<span style="color: #0000ff;">4</span></li>
</ul>
<p>プロジェクト作成については「<a href="http://memories.zal.jp/WP/20110508_2056.html" target="_blank">新規 Android プロジェクトを作成する</a>」の記事に詳しく書いたので参考にしてください。パッケージ名については公開するつもりもないので、とりあえずローカル環境用という意味合いで「localhost」にしました。</p>
<div class="title-blue-line-middle" style="margin-top: 50px;">カスタムボタン用の画像準備</div>
<div style="border: 1px solid #c0c0c0; padding: 10px; margin-top: 20px;">Copy the images on the right into the <span style="color: #008000;">res/drawable/</span> directory of your project. These will be used for the different button states.</div>
<p>[訳]<br />
右の画像をあなたのプロジェクトの<span style="color: #008000;">res/drawable</span>ディレクトリにコピーしてください。これらは異なるボタン状態で使われます。</p>
<p><img style="float: left; margin-right: 10px;" title="android_pressed" src="http://memories.zal.jp/WP/wp-content/uploads/2011/11/android_pressed.png" alt="" width="50" height="58" /><img style="float: left; margin-right: 10px;" title="android_focused" src="http://memories.zal.jp/WP/wp-content/uploads/2011/11/android_focused.png" alt="" width="50" height="58" /><img title="android_normal" src="http://memories.zal.jp/WP/wp-content/uploads/2011/11/android_normal.png" alt="" width="50" height="58" /></p>
<p style="margin-top: 10px;">[補足]<br />
Androidチュートリアルに表示されている画像を上記にも表示しました。上記画像を<span style="color: #008000;">res/drawable</span>ディレクトリに保存してもらっても構いません。また</p>
<ul>
<li>基本状態：android_pressed.png</li>
<li>フォーカス状態：android_focused.png</li>
<li>クリック状態：android_pressed.png</li>
</ul>
<p>上記ファイル名でオリジナル画像にしてもらっても構いません。</p>
<div class="title-blue-line-middle" style="margin-top: 50px;">android_button.xmlの作成</div>
<div style="border: 1px solid #c0c0c0; padding: 10px; margin-top: 20px;">Create a new file in the <span style="color: #008000;">res/drawable/</span> directory named <span style="color: #008000;">android_button.xml</span>. Insert the following XML:</div>
<p style="margin-bottom: 30px;">[訳]<br />
<span style="color: #008000;">res/drawable/</span>ディレクトリに<span style="color: #008000;">android_button.xml</span>という名前で新しいファイルを作ってください。次のXMLを挿入してください。</p>
<pre class="brush: java;">&lt;?xml version="1.0" encoding="utf-8"?&gt;
&lt;selector
    xmlns:android="http://schemas.android.com/apk/res/android"&gt;
    &lt;item android:drawable="@drawable/android_pressed"
          android:state_pressed="true" /&gt;
    &lt;item android:drawable="@drawable/android_focused"
          android:state_focused="true" /&gt;
    &lt;item android:drawable="@drawable/android_normal" /&gt;
&lt;/selector&gt;</pre>
<div style="border: 1px solid #c0c0c0; padding: 10px; margin-top: 20px;">This defines a single drawable resource, which will change its image based on the current state of the button. The first <span style="color: #008000;"><code>&lt;item&gt;</code></span> defines <span style="color: #008000;"><code>android_pressed.png</code></span> as the image when the button is pressed (it's been activated); the second <span style="color: #008000;"><code>&lt;item&gt;</code></span> defines <span style="color: #008000;"><code>android_focused.png</code></span> as the image when the button is focused (when the button is highlighted using the trackball or directional pad); and the third <span style="color: #008000;"><code>&lt;item&gt;</code></span> defines <span style="color: #008000;"><code>android_normal.png</code></span> as the image for the normal state (when neither pressed nor focused). This XML file now represents a single drawable resource and when referenced by a <code><a href="http://developer.android.com/reference/android/widget/Button.html">Button</a></code> for its background, the image displayed will change based on these three states.</div>
<p style="margin-bottom: 30px;">[訳]<br />
ここでは1つのdrawableリソースを定義し、現在のボタンの状態に基づいて画像を変化させます。最初の<span style="color: #008000;">&lt;item&gt;</span>はボタンが押されている（アクティブ状態）のときの画像として<span style="color: #008000;">android_pressed.png</span>を定義しています。2番目の<span style="color: #008000;">&lt;item&gt;</span>はボタンがフォーカスされている（ボタンがトラックボールや十字キーを使ってハイライトされている）ときの画像として<span style="color: #008000;">android_focused.png</span>を定義しています。そして3番目の<span style="color: #008000;">&lt;item&gt;</span>は通常の状態（押されてもフォーカスもされていない）ときの画像として<span style="color: #008000;">android_normal.png</span>を定義しています。このXMLファイルは今1つのdrawableリソースを表し、レイアウトファイルでButton:background属性にによって参照されると、表示される画像はこれら3つの状態に基づいて変化します。</p>
<div style="border: 1px solid #c0c0c0; padding: 10px; margin-top: 50px;"><strong>Note:</strong> The order of the<span style="color: #008000;"> <code>&lt;item&gt;</code></span> elements is important. When this drawable is referenced, the <span style="color: #008000;"> <code>&lt;item&gt;</code></span>s are traversed in-order to determine which one is appropriate for the current button state. Because the "normal" image is last, it is only applied when the conditions <span style="color: #008000;"><code>android:state_pressed</code></span> and <span style="color: #008000;"><code>android:state_focused</code></span> have both evaluated false.</div>
<p>[訳]<br />
<strong>メモ：</strong><span style="color: #008000;">&lt;item&gt;</span>エレメントの順番は重要です。このdrawableが参照されたとき、現在のボタン状態に適切なものを決めるために<span style="color: #008000;">&lt;item&gt;</span>を順番にみていきます。"通常"画像が最後にあるのは、<span style="color: #008000;">android:state_pressed</span>と<span style="color: #008000;">android:state_focused</span>の状態が両方ともfalseと判定されたときに単に適用させる為です。</p>
<p><img class="aligncenter size-full wp-image-2183" title="android119" src="http://memories.zal.jp/WP/wp-content/uploads/2011/11/android1191.jpg" alt="" width="500" height="112" /></p>
<div class="title-blue-line-middle" style="margin-top: 50px;">レイアウトファイルの作成(main.xml)</div>
<div style="border: 1px solid #c0c0c0; padding: 10px; margin-top: 20px;">Open the <span style="color: #008000;">res/layout/main.xml </span>file and add the Button element:</div>
<p>[訳]<br />
<span style="color: #008000;">res/layout/main.xml</span> ファイルを開き、ボタンエレメントを追加します。</p>
<pre class="brush: java;">&lt;?xml version="1.0" encoding="utf-8"?&gt;
&lt;LinearLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    &gt;
   &lt;Button
        android:id="@+id/button"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:padding="10dp"
        android:background="@drawable/android_button" /&gt;
&lt;/LinearLayout&gt;</pre>
<p style="margin-bottom: 30px;">※チュートリアルではボタンエレメントの追加部分だけ記載されていましたが、この記事ではres/layout/main.xml の全コードを記載しておきます。</p>
<div style="border: 1px solid #c0c0c0; padding: 10px; margin-top: 20px;">The <span style="color: #008000;"><code>android:background</code></span> attribute specifies the drawable resource to use for the button background (which, when saved at <span style="color: #008000;"><code>res/drawable/android.xml</code></span>, is referenced as <span style="color: #008000;"><code>@drawable/android</code></span>). This replaces the normal background image used for buttons throughout the system. In order for the drawable to change its image based on the button state, the image must be applied to the background.</div>
<p>[訳]<br />
<span style="color: #008000;"><code>android:background</code></span>属性ではボタン背景の為に使うdrawableリソースを指定します(<code><span style="color: #008000;">res/drawable/android.xml</span>で保存されていれば、</code><code><span style="color: #008000;">@drawable/android</span>と指定すれば参照されます）</code>。これによりシステムを通してボタンに使われる通常の背景画像が置き換わります。drawableリソースがボタン状態に基づいて変化させる為には、画像を背景に適用させる必要があります。</p>
<p style="margin-top: 10px;">[補足]<br />
このサンプルでは <code><span style="color: #008000;">res/drawable/android_button.xml</span> で保存してますので</code><code><span style="color: #008000;">@drawable/android_button</span> で参照しています。<br />
</code></p>
<div class="title-blue-line-middle" style="margin-top: 50px;">アクティビティ作成(HelloFormStuff.java)</div>
<div style="border: 1px solid #c0c0c0; padding: 10px; margin-top: 20px;">To make the button do something when pressed, add the following code at the end of the <code><a href="http://developer.android.com/reference/android/app/Activity.html#onCreate%28android.os.Bundle%29" target="_blank">onCreate()</a></code> method:</div>
<p>[訳]<br />
押されたときにボタンになんらかの動作をさせるために<a href="http://developer.android.com/reference/android/app/Activity.html#onCreate%28android.os.Bundle%29" target="_blank">onCreate()</a>メソッドの最後に次のコードを追加します。</p>
<pre class="brush: java;">package localhost.helloview;

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

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

        final Button button = (Button) findViewById(R.id.button);
        button.setOnClickListener(new OnClickListener() {
            public void onClick(View v) {
                // Perform action on clicks
                Toast.makeText(
                	HelloFormStuff.this
                	,"Beep Bop"
                	,Toast.LENGTH_SHORT
                ).show();
            }
        });
    }
}</pre>
<p style="margin-bottom: 30px;">※チュートリアルではリスナーの追加部分だけ記載されていましたが、この記事ではHelloFormStuff.java の全コードを記載しておきます。</p>
<div style="border: 1px solid #c0c0c0; padding: 10px; margin-top: 20px;">This captures the <code><a href="http://developer.android.com/reference/android/widget/Button.html" target="_blank">Button</a></code> from the layout, then adds an <code><a href="http://developer.android.com/reference/android/view/View.OnClickListener.html" target="_blank">View.OnClickListener</a></code>. The <code><a href="http://developer.android.com/reference/android/view/View.OnClickListener.html" target="_blank">View.OnClickListener</a></code> must implement the <code><a href="http://developer.android.com/reference/android/view/View.OnClickListener.html#onClick%28android.view.View%29" target="_blank">onClick(View)</a></code> callback method, which defines the action to be made when the button is clicked. In this example, a <code><a href="http://developer.android.com/reference/android/widget/Toast.html" target="_blank">Toast</a></code> message will be displayed.</div>
<p>[訳]<br />
ここではレイアウトから<a href="http://developer.android.com/reference/android/widget/Button.html" target="_blank"></a><code><a href="http://developer.android.com/reference/android/widget/Button.html" target="_blank">Button</a></code>インスタンスを取得しそれから<a href="http://developer.android.com/reference/android/view/View.OnClickListener.html" target="_blank"></a><code><a href="http://developer.android.com/reference/android/view/View.OnClickListener.html" target="_blank">View.OnClickListener</a></code>を付与します。<code><a href="http://developer.android.com/reference/android/view/View.OnClickListener.html" target="_blank">View.OnClickListener</a></code>は<code><a href="http://developer.android.com/reference/android/view/View.OnClickListener.html#onClick%28android.view.View%29" target="_blank">onClick(View)</a></code>コールバックメソッドを実装しなければなりません。<code><a href="http://developer.android.com/reference/android/view/View.OnClickListener.html#onClick%28android.view.View%29" target="_blank">onClick(View)</a></code>にはボタンがクリックされたときに処理されるアクションを定義します。例えば、<code><a href="http://developer.android.com/reference/android/widget/Toast.html" target="_blank">Toast</a></code>メッセージを表示させるなどです。</p>
<p style="margin-top: 10px;">[補足]</p>
<ul>
<li> 17行目でレイアウトのIDがbuttonの要素から<code><a href="http://developer.android.com/reference/android/widget/Button.html" target="_blank">Button</a></code>インスタンスを生成しています。</li>
<li>18行目で<code><a href="http://developer.android.com/reference/android/widget/Button.html" target="_blank">Button</a></code>インスタンスに<code><a href="http://developer.android.com/reference/android/view/View.OnClickListener.html" target="_blank">OnClickListener</a></code>リスナーを付与しています。<code><a href="http://developer.android.com/reference/android/view/View.OnClickListener.html" target="_blank">OnClickListener</a></code>はインターフェースなので実装する場合はonClickメソッドをオーバーライドしなければなりません。</li>
<li>19行目でonClickメソッドをオーバーライドしています。</li>
<li>20～25行目ではクリックされたときの処理が書かれており、このサンプルでは「Beep Bop」という<code><a href="http://developer.android.com/reference/android/widget/Toast.html" target="_blank">Toast</a></code>メッセージを表示させます。</li>
</ul>
<div class="title-blue-line-middle" style="margin-top: 50px;">AVDによる実行</div>
<p>AVDによるアプリケーションの実行については「<a href="http://memories.zal.jp/WP/20110516_2073.html#app_excute" target="_blank">AVDでアプリケーションを実行する</a>」の記事で詳しく書きました。参考にしてください。</p>
<p>実行結果をみてみます。次のような画面が表示されました。</p>
<p><img class="aligncenter size-full wp-image-2184" title="android120" src="http://memories.zal.jp/WP/wp-content/uploads/2011/11/android120.jpg" alt="" width="500" height="462" /></p>
]]></content:encoded>
			<wfw:commentRss>http://memories.zal.jp/WP/blog/20111115_2178.html/feed</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Time Picker について</title>
		<link>http://memories.zal.jp/WP/blog/20110911_2172.html</link>
		<comments>http://memories.zal.jp/WP/blog/20110911_2172.html#comments</comments>
		<pubDate>Sun, 11 Sep 2011 12:12:22 +0000</pubDate>
		<dc:creator>admin</dc:creator>
				<category><![CDATA[Android]]></category>
		<category><![CDATA[Hello_Views]]></category>

		<guid isPermaLink="false">http://memories.zal.jp/WP/?p=2172</guid>
		<description><![CDATA[Android developers による「Hello Views」チュートリアルで紹介されているウィジットには次のようなものがあります。 Date Picker Time Picker Form Stuff Spinner Auto Complete Gallery 今回は「Time Picker」チュートリアルについて日本語への翻訳と内容を補足しながらみていきます。 Time Picker Time Pickerの説明についてみていきます。 To provide a widget for selecting a time, use the TimePicker widget, which allows the user to select the hour and minute in a familiar interface. In this tutorial, you'll create a TimePickerDialog, which presents [...]]]></description>
			<content:encoded><![CDATA[<p><a href="http://developer.android.com/intl/ja/resources/tutorials/views/index.html" target="_blank">Android developers</a> による「Hello Views」チュートリアルで紹介されているウィジットには次のようなものがあります。</p>
<div style="border: 1px solid #c0c0c0; padding: 10px; margin-top: 20px;">
<ol>
<li>Date Picker</li>
<li><span style="color: #ff0000;">Time Picker</span></li>
<li>Form Stuff</li>
<li>Spinner</li>
<li>Auto Complete</li>
<li>Gallery</li>
</ol>
</div>
<p>今回は「<a href="http://developer.android.com/resources/tutorials/views/hello-timepicker.html" target="_blank">Time Picker</a>」チュートリアルについて日本語への翻訳と内容を補足しながらみていきます。</p>
<h2 style="padding-top: 40px; margin-bottom: 20px; padding-bottom: 0px;"><span style="color: #0000ff;">Time Picker</span></h2>
<p>Time Pickerの説明についてみていきます。</p>
<div style="border: 1px solid #c0c0c0; padding: 10px; margin-top: 20px;">
<p>To provide a widget for selecting a time, use the <code><a href="http://developer.android.com/reference/android/widget/TimePicker.html" target="_blank">TimePicker</a></code> widget, which allows the user to select the hour and minute in a familiar interface.</p>
<p>In this tutorial, you'll create a <code><a href="http://developer.android.com/reference/android/app/TimePickerDialog.html" target="_blank">TimePickerDialog</a></code>, which presents the time picker in a floating dialog box at the press of a button. When the time is set by the user, a <code><a href="http://developer.android.com/reference/android/widget/TextView.html" target="_blank">TextView</a></code> will update with the new date.</p>
</div>
<p>[訳]<br />
時間を選択するウィジットを提供するのに <a href="http://developer.android.com/reference/android/widget/TimePicker.html" target="_blank">TimePicker</a>ウィジットを使います。このウィジットを使えばユーザは時、分をなじみ深いインターフェースで選択できます。<br />
<span style="font-family: monospace;">このチュートリアルでは</span> <a href="http://developer.android.com/reference/android/app/TimePickerDialog.html" target="_blank">TimePickerDialog</a>,を作ります。ボタンを押したときにダイアログボックスが浮き上がり時間ピッカーが現れます。ユーザが時間をセットしたときに、<a href="http://developer.android.com/reference/android/widget/TextView.html" target="_blank">TextView</a> が新しい時間で更新されます。</p>
<div class="title-blue-line-middle" style="margin-top: 50px;">プロジェクト</div>
<div style="border: 1px solid #c0c0c0; padding: 10px; margin-top: 20px;">Start a new project named HelloTimePicker.</div>
<p>[訳]<br />
HelloTimePicker という名前の新規プロジェクトを開始します。</p>
<ul style="margin-left: 20px;">
<li>プロジェクト名（Project name）<br />
<span style="color: #0000ff;">HelloTimePicker</span></li>
<li>内容(Contents)<br />
<span style="color: #0000ff;">ワークスペース内に新規プロジェクトを作成</span></li>
<li>ビルド・ターゲット(Build Target)<br />
<span style="color: #0000ff;">Android 1.6</span></li>
<li>アプリケーション名（Application Name）<br />
<span style="color: #0000ff;">HelloTimePicker</span></li>
<li>パッケージ名（Package Name）<br />
<span style="color: #0000ff;">localhost.helloview</span></li>
<li>アクティビティの作成（Create Activity）<br />
<span style="color: #0000ff;">HelloTimePicker</span></li>
<li>最小 SDKバージョン（Min SDK Version）<br />
<span style="color: #0000ff;">4</span></li>
</ul>
<p>プロジェクト作成については「<a href="http://memories.zal.jp/WP/20110508_2056.html" target="_blank">新規 Android プロジェクトを作成する</a>」の記事に詳しく書いたので参考にしてください。パッケージ名については公開するつもりもないので、とりあえずローカル環境用という意味合いで「localhost」にしました。</p>
<div class="title-blue-line-middle" style="margin-top: 50px;">レイアウトファイルの作成</div>
<p>新規プロジェクト作成時に res/layout/main.xml のレイアウトファイルができていますが、次のコードと入れ変えます。</p>
<pre class="brush: java;">&lt;?xml version="1.0" encoding="utf-8"?&gt;
&lt;LinearLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:orientation="vertical"&gt;
    &lt;TextView android:id="@+id/timeDisplay"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text=""/&gt;
    &lt;Button android:id="@+id/pickTime"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Change the time"/&gt;
&lt;/LinearLayout&gt;</pre>
<p><img class="aligncenter size-full wp-image-2175" style="margin-top: 30px;" title="android116" src="http://memories.zal.jp/WP/wp-content/uploads/2011/09/android116.jpg" alt="" width="500" height="219" /></p>
<div class="title-blue-line-middle" style="margin-top: 50px;">アクティビティ作成</div>
<p>src/HelloTimePicker.java を開き以下のコードと差し替えます。チュートリアルは別々に分割されて説明されていますがまとめました。また足りないimport文も追加し完全版を記載しておきます。</p>
<pre class="brush: java;highlight:[24,49,57,66,77]">package localhost.helloview;

import java.util.Calendar;
import android.app.Activity;
import android.app.Dialog;
import android.app.TimePickerDialog;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.TimePicker;

public class HelloTimePicker extends Activity {

	//TextView「@+id/mTimeDisplay」のインスタンス
    private TextView mTimeDisplay;
    //Button「@+id/mPickTime」のインスタンス
    private Button mPickTime;
    //時分
    private int mHour;
    private int mMinute;

    static final int TIME_DIALOG_ID = 0;

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

        // TextView「@+id/timeDisplay」エレメントを取得
        mTimeDisplay = (TextView) findViewById(R.id.timeDisplay);
        // Button「@+id/pickTime」エレメントを取得
        mPickTime = (Button) findViewById(R.id.pickTime);
        //ボタンにクリックリスナ追加
        mPickTime.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {
                showDialog(TIME_DIALOG_ID);
            }
        });

        //現在の時間を取得する
        final Calendar c = Calendar.getInstance();
        mHour = c.get(Calendar.HOUR_OF_DAY);
        mMinute = c.get(Calendar.MINUTE);

        //TextViewの時間を更新するメソッド実行
        updateDisplay();
    }

    //TextViewの時間を更新する
    private void updateDisplay() {
        mTimeDisplay.setText(
            new StringBuilder()
                    .append(pad(mHour)).append(":")
                    .append(pad(mMinute)));
    }

    //時、分の値が1桁の場合に前に0を追加するメソッド
    //※例）8 ⇒ 08など
    private static String pad(int c) {
        if (c &gt;= 10)
            return String.valueOf(c);
        else
            return "0" + String.valueOf(c);
    }

    //時間ダイアログ内の「sets」ボタンクリック時にコールバック
    private TimePickerDialog.OnTimeSetListener mTimeSetListener =
        new TimePickerDialog.OnTimeSetListener() {
            public void onTimeSet(
            	TimePicker view, int hourOfDay, int minute) {
                	mHour = hourOfDay;
                	mMinute = minute;
                	updateDisplay();
            	}
            };

    @Override
    protected Dialog onCreateDialog(int id) {
        switch (id) {
        case TIME_DIALOG_ID:
            return new TimePickerDialog(this,
            	mTimeSetListener, mHour, mMinute, false);
        }
        return null;
    }
}</pre>
<p style="margin-top: 20px;">【15～23行目に関する説明】</p>
<div style="border: 1px solid #c0c0c0; padding: 10px;">This declares variables for the layout elements and time fields. The <span style="color: #008000;"><code>TIME_DIALOG_ID</code></span> is a static integer that uniquely identifies the dialog.</div>
<p style="margin-bottom: 20px;">[訳]<br />
ここではレイアウトエレメント<a href="http://developer.android.com/reference/android/view/View.html" target="_blank"></a> と日付項目に関する変数を定義しています。<span style="color: #008000;">TIME_DIALOG_ID</span>は時間ピッカーを表示するダイアルログに対するユニークな識別子でstatic修飾子のint型で指定しています。</p>
<p>[補足]<br />
mTimeDisplayとmPickTimeがレイアウトエレメント<a href="http://developer.android.com/reference/android/view/View.html" target="_blank"></a>に関するメンバ変数で、mHour、mMinuteが時間に関するメンバ変数です。23行目で<span style="color: #008000;">TIME_DIALOG_ID</span>を定義し「0」を代入していますが、staticとfinal修飾子がついているので定数です。日付ピッカー用のダイアログには「0」という識別子をつけてアクティビティがダイアログを管理します。</p>
<p style="margin-top: 50px;">【26～51行目に関する説明】</p>
<div style="border: 1px solid #c0c0c0; padding: 10px;">First, the content is set to the <span style="color: #008000;"><code>main.xml</code></span> layout and then the <code><a href="http://developer.android.com/reference/android/widget/TextView.html" target="_blank">TextView</a></code> and <code><a href="http://developer.android.com/reference/android/widget/Button.html" target="_blank">Button</a></code> are captured with <code><a href="http://developer.android.com/reference/android/app/Activity.html#findViewById%28int%29" target="_blank">findViewById(int)</a></code>. Then an <code><a href="http://developer.android.com/reference/android/view/View.OnClickListener.html" target="_blank">View.OnClickListener</a></code> is created for the <code><a href="http://developer.android.com/reference/android/widget/Button.html" target="_blank">Button</a></code>, so that when clicked, it will call <code><a href="http://developer.android.com/reference/android/app/Activity.html#showDialog%28int%29" target="_blank">showDialog(int)</a></code>, passing the unique integer ID for the time picker dialog. Using <code><a href="http://developer.android.com/reference/android/app/Activity.html#showDialog%28int%29" target="_blank">showDialog(int)</a></code> allows the <code><a href="http://developer.android.com/reference/android/app/Activity.html" target="_blank">Activity</a></code> to manage the life-cycle of the dialog and will call the <code><a href="http://developer.android.com/reference/android/app/Activity.html#onCreateDialog%28int%29" target="_blank">onCreateDialog(int)</a></code> callback method to request the <code><a href="http://developer.android.com/reference/android/app/Dialog.html" target="_blank">Dialog</a></code> that should be displayed (which you'll define later). After the on-click listener is set, a new <code><a href="http://developer.android.com/reference/java/util/Calendar.html" target="_blank">Calendar</a></code> is created to get the current hour and minute. Finally, the private <span style="color: #008000;"><code>updateDisplay()</code></span> method is called in order to fill the <code><a href="http://developer.android.com/reference/android/widget/TextView.html" target="_blank">TextView</a></code> with the current time.</div>
<p style="margin-bottom: 20px;">[訳]<br />
最初に<span style="color: #008000;">main.xml</span>レイアウトをコンテンツに設定します。それから TextViewと ButtonエレメントをfindViewById(int)を指定してレイアウトから取得します。ボタンにはView.OnClickListener メソッドでリスナを作ります。これによりボタンをクリックしたときにshowDialog(int)が呼ばれ、パラメータとして時間ピッカーダイアログの為のID（ユニークな数値）を渡します。showDialog(int)により Activity がダイアログのライフサイクルを管理することができ、onCreateDialog(int)コールバックメソッドを呼んで表示するダイアログを要求します（後ほど定義します）。<br />
on-clickリスナが設定された後、新しいCalendarインスタンスが作られ、現在の時、分を取得します。最後に、アクセス修飾子privateのupdateDisplayメソッドが呼ばれ、 TextViewに現在時間で満たします。</p>
<p>[補足]<br />
<img class="aligncenter size-full wp-image-2177" style="margin-top: 10px;" title="android118" src="http://memories.zal.jp/WP/wp-content/uploads/2011/09/android118.jpg" alt="" width="500" height="174" /><br />
onCreateメソッド内の説明です。onCreateはアクティビティが最初に作られたときに呼ばれます。onCreateメソッド内の大体の流れは次のようになります。</p>
<ol>
<li>XML レイアウト ファイルからエレメントを取得してインスタンスを生成</li>
<li>ボタン（<code>Button「@+id/</code><code>pickTime</code><code>」）にクリックリスナを付ける</code></li>
<li>Calendarクラスを利用して現在の時間を取得する</li>
<li>現在の時間をTextViewに表示する。</li>
</ol>
<p>Android XML レイアウトファイルの構造はXML 要素がツリー構造になっており、含まれた各ノードが View クラスの名前を表しています。30～33行目ではXML情報からインスタンスを生成しています。</p>
<p>34～39行目ではボタン（<code>Button「@+id/</code><code>pickTime</code><code>」）にクリックしたときに時間</code>ピッカーダイアログが表示されるようリスナを付けます。この段階ではリスナを付けただけなので時間ピッカーダイアログは表示されていません。</p>
<p>41～44行目ではCalendarクラスを利用して現在の時間を取得しています。時、分を別々に取得し各情報をメンバ変数に代入にしています。</p>
<p>46～47行目ではupdateDisplayメソッドを実行し、TextViewの時間を更新しています。</p>
<p style="margin-top: 50px;">【49～65行目に関する説明】</p>
<div style="border: 1px solid #c0c0c0; padding: 10px;">The <span style="color: #008000;"><code>updateDisplay()</code></span> method uses the member fields for the time and inserts them in the <span style="color: #008000;"><code>mTimeDisplay</code> </span><code><a href="http://developer.android.com/reference/android/widget/TextView.html" target="_blank">TextView</a></code>. The <span style="color: #008000;"><code>pad()</code></span> method returns the appropriate string representation of the hour or minute—it will prefix a zero to the number if it's a single digit.</div>
<p style="margin-bottom: 20px;">[訳]<br />
<span style="color: #008000;">updateDisplay()</span>メソッドは時間に関するメンバ変数の値を使って<span style="color: #008000;">mTimeDisplay</span><a href="http://developer.android.com/reference/android/widget/TextView.html" target="_blank">TextView</a>に値を挿入します。<span style="color: #008000;">pad()</span>メソッドは時間や分を表現する適切な文字列を返します。1桁のときに前に0を付け加えます。</p>
<p>[補足]<br />
padメソッドでは、例えば5時1分の場合「5：1」と表示するのではなく「05:01」と0を付けて2桁に調整します。</p>
<p style="margin-top: 50px;">【66～76行目に関する説明】</p>
<div style="border: 1px solid #c0c0c0; padding: 10px;">When the user is done setting the time (clicks the "Set" button), the <span style="color: #008000;"><code>onTimeSet()</code></span> method is called and it updates the member fields with the new time and updates the layout's <code><a href="http://developer.android.com/reference/android/widget/TextView.html" target="_blank">TextView</a></code>.</div>
<p style="margin-bottom: 20px;">[訳]<br />
ユーザが時間を設定したとき（「Set」ボタンをクリックすることにより）に<span style="color: #008000;">onTimeSet()</span>メソッドが呼ばれます。そして新しい時間で日付に関するメンバが更新され、さらにレイアウト<a href="http://developer.android.com/reference/android/widget/TextView.html" target="_blank">TextView</a>の内容も更新されます。</p>
<p style="margin-top: 50px;">【77～87行目に関する説明】</p>
<div style="border: 1px solid #c0c0c0; padding: 10px;">This is an <code><a href="http://developer.android.com/reference/android/app/Activity.html" target="_blank">Activity</a></code> callback that is passed the identifier you passed to <code><a href="http://developer.android.com/reference/android/app/Activity.html#showDialog%28int%29" target="_blank">showDialog(int)</a></code>, in the <code><a href="http://developer.android.com/reference/android/widget/Button.html" target="_blank">Button</a></code>'s on-click listener. When the ID matches, this initializes the <code><a href="http://developer.android.com/reference/android/app/TimePickerDialog.html" target="_blank">TimePickerDialog</a></code> with the member variables initialized at the end of <span style="color: #008000;"><code>onCreate()</code></span> and the <code><a href="http://developer.android.com/reference/android/app/TimePickerDialog.OnTimeSetListener.html" target="_blank">TimePickerDialog.OnTimeSetListener</a></code> created in the previous step.</div>
<p style="margin-bottom: 20px;">[訳]<br />
このメソッドは<a href="http://developer.android.com/reference/android/app/Activity.html" target="_blank">Activity</a>コールメソッドであり、<a href="http://developer.android.com/reference/android/app/Activity.html#showDialog%28int%29" target="_blank">showDialog(int)</a>に与えられた識別子が引数として渡されます（ボタンのon-clickリスナによって呼ばれます）。switch case構文でIDが一致すれば、<a href="http://developer.android.com/reference/android/app/TimePickerDialog.html" target="_blank">TimePickerDialog</a>はonCreate() の最後で初期化された日付メンバと前のステップで作成された<a href="http://developer.android.com/reference/android/app/TimePickerDialog.OnTimeSetListener.html" target="_blank">TimePickerDialog.OnTimeSetListener</a>で初期化されます。</p>
<p>[補足]<br />
showDialog(int)により Activity がダイアログのライフサイクルを管理しています。showDialogが呼び出されると最初の一回だけonCreateDialog()がコールされダイアログを作成します。ここで作成されたダイアログは自動的に保存されいつでも呼び出すことができるようになります。</p>
<div class="title-blue-line-middle" style="margin-top: 50px;">AVDによる実行</div>
<p>AVDによるアプリケーションの実行については「<a href="http://memories.zal.jp/WP/20110516_2073.html#app_excute" target="_blank">AVDでアプリケーションを実行する</a>」の記事で詳しく書きました。参考にしてください。</p>
<p>実行結果をみてみます。次のような画面が表示されました。</p>
<p><img class="aligncenter size-full wp-image-2176" title="android117" src="http://memories.zal.jp/WP/wp-content/uploads/2011/09/android117.jpg" alt="" width="500" height="460" /></p>
]]></content:encoded>
			<wfw:commentRss>http://memories.zal.jp/WP/blog/20110911_2172.html/feed</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Date Picker について</title>
		<link>http://memories.zal.jp/WP/blog/20110831_2168.html</link>
		<comments>http://memories.zal.jp/WP/blog/20110831_2168.html#comments</comments>
		<pubDate>Tue, 30 Aug 2011 17:06:06 +0000</pubDate>
		<dc:creator>admin</dc:creator>
				<category><![CDATA[Android]]></category>
		<category><![CDATA[Hello_Views]]></category>

		<guid isPermaLink="false">http://memories.zal.jp/WP/?p=2168</guid>
		<description><![CDATA[今回からウィジットについてみていきます。Android developers による「Hello Views」チュートリアルで紹介されているウィジットには次のようなものがあります。 Date Picker Time Picker Form Stuff Spinner Auto Complete Gallery 今回は「Date Picker」チュートリアルについて日本語への翻訳と内容を補足しながらみていきます。 Date Picker Date Picker の概要 Date Pickerの説明についてみていきます。 To provide a widget for selecting a date, use the DatePicker widget, which allows the user to select the month, day, and year, in a familiar interface. In this tutorial, you'll create [...]]]></description>
			<content:encoded><![CDATA[<p>今回からウィジットについてみていきます。<a href="http://developer.android.com/intl/ja/resources/tutorials/views/index.html" target="_blank">Android developers</a> による「Hello Views」チュートリアルで紹介されているウィジットには次のようなものがあります。</p>
<div style="border: 1px solid #c0c0c0; padding: 10px; margin-top: 20px;">
<ol>
<li><span style="color: #ff0000;">Date Picker</span></li>
<li>Time Picker</li>
<li>Form Stuff</li>
<li>Spinner</li>
<li>Auto Complete</li>
<li>Gallery</li>
</ol>
</div>
<p>今回は「<a href="http://developer.android.com/intl/ja/resources/tutorials/views/hello-datepicker.html" target="_blank">Date Picker</a>」チュートリアルについて日本語への翻訳と内容を補足しながらみていきます。</p>
<h2 style="padding-top: 40px; margin-bottom: 20px; padding-bottom: 0px;"><span style="color: #0000ff;">Date Picker</span></h2>
<div class="title-blue-line-middle" style="margin-top: 10px;">Date Picker の概要</div>
<p>Date Pickerの説明についてみていきます。</p>
<div style="border: 1px solid #c0c0c0; padding: 10px; margin-top: 20px;">
<p>To provide a widget for selecting a date, use the <code><a href="http://developer.android.com/reference/android/widget/DatePicker.html" target="_blank">DatePicker</a></code> widget, which allows the user to select the month, day, and year, in a familiar interface.</p>
<p>In this tutorial, you'll create a <code><a href="http://developer.android.com/reference/android/app/DatePickerDialog.html" target="_blank">DatePickerDialog</a></code>, which presents the date picker in a floating dialog box at the press of a button. When the date is set by the user, a <code><a href="http://developer.android.com/reference/android/widget/TextView.html" target="_blank">TextView</a></code> will update with the new date.</p>
</div>
<p>[訳]<br />
日付を選択するウィジットを提供するのに <a href="http://developer.android.com/reference/android/widget/DatePicker.html" target="_blank">DatePicker</a>ウィジットを使います。このウィジットを使えばユーザは月、日、年をなじみ深いインターフェースで選択できます。<br />
このチュートリアルでは<a href="http://developer.android.com/reference/android/app/DatePickerDialog.html" target="_blank">DatePickerDialog</a>を作ります。ボタンを押したときにダイアログボックスが浮き上がり日付ピッカーが現れます。ユーザが日付をセットしたときに、<a href="http://developer.android.com/reference/android/widget/TextView.html" target="_blank">TextView</a> が新しい日付で更新されます。</p>
<p><span id="more-2168"></span></p>
<div class="title-blue-line-middle" style="margin-top: 50px;">プロジェクト</div>
<div style="border: 1px solid #c0c0c0; padding: 10px; margin-top: 20px;">Start a new project named HelloDatePicker.</div>
<p>[訳]<br />
<em>HelloDatePicker</em> という名前の新規プロジェクトを開始します。</p>
<ul style="margin-left: 20px;">
<li>プロジェクト名（Project name）<br />
<span style="color: #0000ff;">HelloDatePicker</span></li>
<li>内容(Contents)<br />
<span style="color: #0000ff;">ワークスペース内に新規プロジェクトを作成</span></li>
<li>ビルド・ターゲット(Build Target)<br />
<span style="color: #0000ff;">Android 1.6</span></li>
<li>アプリケーション名（Application Name）<br />
<span style="color: #0000ff;">HelloDatePicker</span></li>
<li>パッケージ名（Package Name）<br />
<span style="color: #0000ff;">localhost.helloview</span></li>
<li>アクティビティの作成（Create Activity）<br />
<span style="color: #0000ff;">HelloDatePicker</span></li>
<li>最小 SDKバージョン（Min SDK Version）<br />
<span style="color: #0000ff;">4</span></li>
</ul>
<p>プロジェクト作成については「<a href="http://memories.zal.jp/WP/20110508_2056.html" target="_blank">新規 Android プロジェクトを作成する</a>」の記事に詳しく書いたので参考にしてください。パッケージ名については公開するつもりもないので、とりあえずローカル環境用という意味合いで「localhost」にしました。</p>
<div class="title-blue-line-middle" style="margin-top: 50px;">レイアウトファイルの作成</div>
<p>新規プロジェクト作成時に res/layout/main.xml のレイアウトファイルができていますが、次のコードと入れ変えます。</p>
<pre class="brush: java;">&lt;?xml version="1.0" encoding="utf-8"?&gt;
&lt;LinearLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:orientation="vertical"&gt;
    &lt;TextView android:id="@+id/dateDisplay"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text=""/&gt;
    &lt;Button android:id="@+id/pickDate"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Change the date"/&gt;
&lt;/LinearLayout&gt;</pre>
<p><img class="aligncenter size-full wp-image-2169" style="margin-top: 30px;" title="android112" src="http://memories.zal.jp/WP/wp-content/uploads/2011/08/android112.jpg" alt="" width="500" height="222" /></p>
<div class="title-blue-line-middle" style="margin-top: 50px;">アクティビティ作成</div>
<p>src/HelloDatePicker.java を開き以下のコードと差し替えます。チュートリアルは別々に分割されて説明されていますがまとめました。また足りないimport文も追加し完全版を記載しておきます。</p>
<pre class="brush: java;highlight:[25,52,62,76]">package localhost.helloview;

import java.util.Calendar;
import android.app.Activity;
import android.app.DatePickerDialog;
import android.app.Dialog;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.TextView;

public class HelloDatePicker extends Activity {

	//TextView「@+id/dateDisplay」のインスタンス
	private TextView mDateDisplay;
	//Button「@+id/pickDate」のインスタンス
    private Button mPickDate;
    //日付
    private int mYear;	//年
    private int mMonth;	//月
    private int mDay;	//日

    static final int DATE_DIALOG_ID = 0;

	/** Called when the activity is first created. */
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);

        // TextView「@+id/dateDisplay」エレメントを取得
        mDateDisplay = (TextView) findViewById(R.id.dateDisplay);
        // Button「@+id/pickDate」エレメントを取得
        mPickDate = (Button) findViewById(R.id.pickDate);
        //ボタンにクリックリスナ追加
        mPickDate.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {
                showDialog(DATE_DIALOG_ID);
            }
        });

        //現在の日付を取得する
        final Calendar c = Calendar.getInstance();
        mYear = c.get(Calendar.YEAR);
        mMonth = c.get(Calendar.MONTH);
        mDay = c.get(Calendar.DAY_OF_MONTH);

        //TextViewの日付を更新するメソッド実行
        updateDisplay();
    }

    //TextViewの日付を更新する
    private void updateDisplay() {
        mDateDisplay.setText(
            new StringBuilder()
                 //月は「0～11」の値を取るので表示は+1
                 .append(mMonth + 1).append("-")
                 .append(mDay).append("-")
                 .append(mYear).append(" "));
    }

    //日付ダイアログ内の「sets」ボタンクリック時にコールバック
    private DatePickerDialog.OnDateSetListener mDateSetListener =
            new DatePickerDialog.OnDateSetListener() {
                public void onDateSet(
                		DatePicker view, int year,
                        int monthOfYear, int dayOfMonth
                ){
                    mYear = year;
                    mMonth = monthOfYear;
                    mDay = dayOfMonth;
                    updateDisplay();
                }
            };

    @Override
    protected Dialog onCreateDialog(int id) {
        switch (id) {
        case DATE_DIALOG_ID:
            return new DatePickerDialog(
            			this,
                        mDateSetListener,
                        mYear, mMonth, mDay);
        }
        return null;
    }
}</pre>
<p style="margin-top: 20px;">【15～24行目に関する説明】</p>
<div style="border: 1px solid #c0c0c0; padding: 10px;">The first group of members define variables for the layout <code><a href="http://developer.android.com/reference/android/view/View.html" target="_blank">View</a></code>s and the date items. The <span style="color: #008000;"><code>DATE_DIALOG_ID</code></span> is a static integer that uniquely identifies the <code><a href="http://developer.android.com/reference/android/app/Dialog.html" target="_blank">Dialog</a></code> that will display the date picker.</div>
<p style="margin-bottom: 20px;">[訳]<br />
メンバの最初のグループでレイアウト<a href="http://developer.android.com/reference/android/view/View.html" target="_blank">View</a> と日付項目に関する変数を定義しています。<span style="color: #008000;">DATE_DIALOG_ID</span>は日付ピッカーを表示するダイアルログに対するユニークな識別子でstatic修飾子のint型で指定しています。</p>
<p>[補足]<br />
mDateDisplayとmPickDateがレイアウト<a href="http://developer.android.com/reference/android/view/View.html" target="_blank">View</a>に関するメンバ変数で、mYear、mMonth、mDayが日付に関するメンバ変数です。24行目で<span style="color: #008000;">DATE_DIALOG_ID</span>を定義し「0」を代入していますが、staticとfinal修飾子がついているので定数です。日付ピッカー用のダイアログには「0」という識別子をつけてアクティビティがダイアログを管理します。</p>
<p style="margin-top: 50px;">【26～51行目に関する説明】</p>
<div style="border: 1px solid #c0c0c0; padding: 10px;">First, the content is set to the <span style="color: #008000;"><code>main.xml</code></span> layout. Then the <code><a href="http://developer.android.com/reference/android/widget/TextView.html" target="_blank">TextView</a></code> and <code><a href="http://developer.android.com/reference/android/widget/Button.html" target="_blank">Button</a></code> elements are captured from the layout with <code><a href="http://developer.android.com/reference/android/app/Activity.html#findViewById%28int%29" target="_blank">findViewById(int)</a></code>. A new <code><a href="http://developer.android.com/reference/android/view/View.OnClickListener.html" target="_blank">View.OnClickListener</a></code> is created for the <code><a href="http://developer.android.com/reference/android/widget/Button.html" target="_blank">Button</a></code>, so that when it is clicked, it will call <code><a href="http://developer.android.com/reference/android/app/Activity.html#showDialog%28int%29" target="_blank">showDialog(int)</a></code>, passing the unique integer ID for the date picker dialog. Using <code><a href="http://developer.android.com/reference/android/app/Activity.html#showDialog%28int%29" target="_blank">showDialog(int)</a></code> allows the <code><a href="http://developer.android.com/reference/android/app/Activity.html" target="_blank">Activity</a></code> to manage the life-cycle of the dialog and will call the <code><a href="http://developer.android.com/reference/android/app/Activity.html#onCreateDialog%28int%29" target="_blank">onCreateDialog(int)</a></code> callback method to request the <code><a href="http://developer.android.com/reference/android/app/Dialog.html" target="_blank">Dialog</a></code> that should be displayed (which you'll define later). After the on-click listener is set, a new <code><a href="http://developer.android.com/reference/java/util/Calendar.html" target="_blank">Calendar</a></code> is created and the current year, month and day are acquired. Finally, the private<span style="color: #008000;"> <code>updateDisplay()</code></span> method is called in order to fill the <code><a href="http://developer.android.com/reference/android/widget/TextView.html" target="_blank">TextView</a></code> with the current date.</div>
<p style="margin-bottom: 20px;">[訳]<br />
最初にmain.xmlレイアウトをコンテンツに設定します。それから TextViewと ButtonエレメントをfindViewById(int)を指定してレイアウトから取得します。ボタンには新たにView.OnClickListener メソッドでリスナを作ります。これによりボタンをクリックしたときにshowDialog(int)が呼ばれ、パラメータとして日付ピッカーダイアログの為のID（ユニークな数値）を渡します。showDialog(int)により Activity がダイアログのライフサイクルを管理することができ、onCreateDialog(int)コールバックメソッドを呼んで表示するダイアログを要求します（後ほど定義します）。<br />
on-clickリスナが設定された後、新しいCalendarが作られ、現在の年、月、日を取得します。最後に、アクセス修飾子privateのupdateDisplayメソッドが呼ばれ、 TextViewに現在日付で満たします。</p>
<p>[補足]<br />
<img class="aligncenter size-full wp-image-2170" title="android113" src="http://memories.zal.jp/WP/wp-content/uploads/2011/08/android113.jpg" alt="" width="500" height="177" /><br />
onCreateメソッド内の説明です。onCreateはアクティビティが最初に作られたときに呼ばれます。onCreateメソッド内の大体の流れは次のようになります。</p>
<ol>
<li>XML レイアウト ファイルからエレメントを取得してインスタンスを生成</li>
<li>ボタン（<code>Button「@+id/pickDate」）にクリックリスナを付ける</code></li>
<li>Calendarクラスを利用して現在の日付を取得する</li>
<li>現在の日付をTextViewに表示する。</li>
</ol>
<p>Android XML レイアウトファイルの構造はXML 要素がツリー構造になっており、含まれた各ノードが View クラスの名前を表しています。32～35行目ではXML情報からインスタンスを生成しています。<br />
36～41行目ではボタン（<code>Button「@+id/pickDate」）にクリックしたときに</code>日付ピッカーダイアログが表示されるようリスナを付けます。この段階ではリスナを付けただけなので日付ピッカーダイアログは表示されていません。<br />
43～47行目ではCalendarクラスを利用して現在の日付を取得しています。年、月、日を別々に取得し各情報をメンバ変数に代入にしています。<br />
49～51行目ではupdateDisplayメソッドを実行し、TextViewの日付を更新しています。</p>
<p style="margin-top: 50px;">【52～61行目に関する説明】</p>
<div style="border: 1px solid #c0c0c0; padding: 10px;">This method uses the member date values declared for the class to write the date to the layout's <code><a href="http://developer.android.com/reference/android/widget/TextView.html" target="_blank">TextView</a></code>, <code>mDateDisplay</code>, which was also declared and initialized above.</div>
<p style="margin-bottom: 20px;">[訳]<br />
このメソッドはメンバ変数の値を使います。レイアウトTextViewに日付を書き込むため、これらのメンバ変数をクラスに宣言しました。メンバ変数は上記で宣言され初期化されています。</p>
<p>[補足]</p>
<pre class="brush: java;first-line:58">.append(mMonth + 1).append("-")</pre>
<p>カレンダークラスや日付ピッカーで取得する月の値は0～11の範囲を取るので+1をして表示します。</p>
<p style="margin-top: 50px;">【62～75行目に関する説明】</p>
<div style="border: 1px solid #c0c0c0; padding: 10px;">The <code><a href="http://developer.android.com/reference/android/app/DatePickerDialog.OnDateSetListener.html" target="_blank">DatePickerDialog.OnDateSetListener</a></code> listens for when the user has set the date (by clicking the "Set" button). At that time, the <code><a href="http://developer.android.com/reference/android/app/DatePickerDialog.OnDateSetListener.html#onDateSet%28android.widget.DatePicker,%20int,%20int,%20int%29" target="_blank">onDateSet()</a></code> callback method is called, which is defined to update the <span style="color: #339966;"><code>mYear</code></span>, <span style="color: #339966;"><code>mMonth</code></span>, and <span style="color: #339966;"><code>mDay</code> </span>member fields with the new date then call the private <code>updateDisplay()</code> method to update the <code><a href="http://developer.android.com/reference/android/widget/TextView.html" target="_blank">TextView</a></code>.</div>
<p style="margin-bottom: 20px;">[訳]<br />
DatePickerDialog.OnDateSetListenerのリスナはユーザが日付を設定したとき（「Set」ボタンをクリックすることにより）に処理が走ります。その時 onDateSet() コールバックメソッドが呼ばれ、mYear、mMonth、そしてmDay のメンバ変数の値を新しい日付で更新します。それからアクセス修飾子privateのupdateDisplay() メソッドが呼ばれTextViewの内容を更新します。</p>
<p style="margin-top: 50px;">【76～88行目に関する説明】</p>
<div style="border: 1px solid #c0c0c0; padding: 10px;">This is an <code><a href="http://developer.android.com/reference/android/app/Activity.html" target="_blank">Activity</a></code> callback method that is passed the integer ID given to <code><a href="http://developer.android.com/reference/android/app/Activity.html#showDialog%28int%29" target="_blank">showDialog(int)</a></code> (which is called by the button's <code><a href="http://developer.android.com/reference/android/view/View.OnClickListener.html" target="_blank">View.OnClickListener</a></code>). When the ID matches the switch case defined here, a <code><a href="http://developer.android.com/reference/android/app/DatePickerDialog.html" target="_blank">DatePickerDialog</a></code> is instantiated with the <code><a href="http://developer.android.com/reference/android/app/DatePickerDialog.OnDateSetListener.html" target="_blank">DatePickerDialog.OnDateSetListener</a></code> created in the previous step, along with the date variables to initialize the widget date.</div>
<p style="margin-bottom: 20px;">[訳]<br />
このメソッドはActivityコールメソッドであり、showDialog(int)に与えられたID（数値型）が引数として渡されます（ボタンのView.OnClickListererによって呼ばれます）。ここで定義されたswitch case構文でIDが一致すれば、DatePickerDialogのインスタンスが作られます。このインスタンス化には前ステップで作られたDatePickerDialog.OnDateSetListener、そしてwidgetの日付を初期化する為の日付変数をパラメータとして渡します。</p>
<p>[補足]<br />
showDialog(int)により Activity がダイアログのライフサイクルを管理しています。showDialogが呼び出されると最初の一回だけonCreateDialog()がコールされダイアログを作成します。ここで作成されたダイアログは自動的に保存されいつでも呼び出すことができるようになります。</p>
<div class="title-blue-line-middle" style="margin-top: 50px;">AVDによる実行</div>
<p>AVDによるアプリケーションの実行については「<a href="http://memories.zal.jp/WP/20110516_2073.html#app_excute" target="_blank">AVDでアプリケーションを実行する</a>」の記事で詳しく書きました。参考にしてください。</p>
<p>実行結果をみてみます。次のような画面が表示されました。</p>
<p><img class="aligncenter size-full wp-image-2171" title="android114" src="http://memories.zal.jp/WP/wp-content/uploads/2011/08/android114.jpg" alt="" width="500" height="458" /></p>
]]></content:encoded>
			<wfw:commentRss>http://memories.zal.jp/WP/blog/20110831_2168.html/feed</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>List View について</title>
		<link>http://memories.zal.jp/WP/blog/20110817_2162.html</link>
		<comments>http://memories.zal.jp/WP/blog/20110817_2162.html#comments</comments>
		<pubDate>Tue, 16 Aug 2011 16:58:23 +0000</pubDate>
		<dc:creator>admin</dc:creator>
				<category><![CDATA[Android]]></category>
		<category><![CDATA[Hello_Views]]></category>

		<guid isPermaLink="false">http://memories.zal.jp/WP/?p=2162</guid>
		<description><![CDATA[Android developers による「Hello Views」チュートリアルで紹介されているレイアウトには次のようなものがあります。 Linear Layout Relative Layout Table Layout Grid View Tab Layout List View 今回は「List View」チュートリアルについて日本語への翻訳と内容を補足しながらみていきます。 List View List View の概要 List Viewの説明についてみていきます。 ListView is a ViewGroup that creates a list of scrollable items. The list items are automatically inserted to the list using a ListAdapter. In this tutorial, you'll create a scrollable [...]]]></description>
			<content:encoded><![CDATA[<p><a href="http://developer.android.com/intl/ja/resources/tutorials/views/index.html" target="_blank">Android developers</a> による「Hello Views」チュートリアルで紹介されているレイアウトには次のようなものがあります。</p>
<div style="border: 1px solid #c0c0c0; padding: 10px; margin-top: 20px;">
<ol>
<li>Linear Layout</li>
<li>Relative Layout</li>
<li>Table Layout</li>
<li>Grid View</li>
<li>Tab Layout</li>
<li><span style="color: #ff0000;">List View</span></li>
</ol>
</div>
<p>今回は「<a href="http://developer.android.com/intl/ja/resources/tutorials/views/hello-listview.html" target="_blank">List View</a>」チュートリアルについて日本語への翻訳と内容を補足しながらみていきます。</p>
<h2 style="padding-top: 40px; margin-bottom: 20px; padding-bottom: 0px;"><span style="color: #0000ff;">List View</span></h2>
<div class="title-blue-line-middle" style="margin-top: 50px;">List View の概要</div>
<p>List Viewの説明についてみていきます。</p>
<div style="border: 1px solid #c0c0c0; padding: 10px; margin-top: 20px;">
<p><code><a href="http://developer.android.com/reference/android/widget/ListView.html" target="_blank">ListView</a></code> is a <code><a href="http://developer.android.com/reference/android/view/ViewGroup.html" target="_blank">ViewGroup</a></code> that creates a list of scrollable items. The list items are automatically inserted to the list using a <code><a href="http://developer.android.com/reference/android/widget/ListAdapter.html" target="_blank">ListAdapter</a></code>.</p>
<p>In this tutorial, you'll create a scrollable list of country names that are read from a string array. When a list item is selected, a toast message will display the position of the item in the list.</p>
</div>
<p>[訳]<br />
<a href="http://developer.android.com/reference/android/widget/ListView.html" target="_blank">ListView</a>はスクロール可能な項目のリストを作る<a href="http://developer.android.com/reference/android/view/ViewGroup.html" target="_blank">ViewGroup</a>です。リスト項目は<a href="http://developer.android.com/reference/android/widget/ListAdapter.html" target="_blank">ListAdapter</a>を使って自動的にリストに挿入されます。<br />
このチュートリアルでは文字列配列から国名を読み込み、スクロール可能な国名リストを作ります。リスト項目が選択されたときは、そのリストでの項目の位置をトーストメッセージで表示します。</p>
<p><span id="more-2162"></span></p>
<div class="title-blue-line-middle" style="margin-top: 50px;">プロジェクト</div>
<div style="border: 1px solid #c0c0c0; padding: 10px; margin-top: 20px;">Start a new project named <em>HelloListView</em>.</div>
<p>[訳]<br />
<em>HelloListView</em> という名前の新規プロジェクトを開始します。</p>
<ul style="margin-left: 20px;">
<li>プロジェクト名（Project name）<br />
<span style="color: #0000ff;">HelloListView</span></li>
<li>内容(Contents)<br />
<span style="color: #0000ff;">ワークスペース内に新規プロジェクトを作成</span></li>
<li>ビルド・ターゲット(Build Target)<br />
<span style="color: #0000ff;">Android 1.6</span></li>
<li>アプリケーション名（Application Name）<br />
<span style="color: #0000ff;">HelloListView</span></li>
<li>パッケージ名（Package Name）<br />
<span style="color: #0000ff;">localhost.helloview</span></li>
<li>アクティビティの作成（Create Activity）<br />
<span style="color: #0000ff;">HelloListView</span></li>
<li>最小 SDKバージョン（Min SDK Version）<br />
<span style="color: #0000ff;">4</span></li>
</ul>
<p>プロジェクト作成については「<a href="http://memories.zal.jp/WP/20110508_2056.html" target="_blank">新規 Android プロジェクトを作成する</a>」の記事に詳しく書いたので参考にしてください。パッケージ名については公開するつもりもないので、とりあえずローカル環境用という意味合いで「localhost」にしました。</p>
<div class="title-blue-line-middle" style="margin-top: 50px;">レイアウトファイルの作成</div>
<p>list_item.xml という名前のxmlファイルを作成し、/res/layout/　に保存します。list_item.xml のコードを次のコードと入れ変えます。</p>
<pre class="brush: java;">&lt;?xml version="1.0" encoding="utf-8"?&gt;
&lt;TextView
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:padding="10dp"
    android:textSize="16sp" &gt;
&lt;/TextView&gt;</pre>
<div class="title-blue-line-middle" style="margin-top: 50px;">アクティビティ作成</div>
<p>src/HelloListView.java を開きスーパークラスを<a href="http://developer.android.com/reference/android/app/TabActivity.html" target="_blank"></a><code><a href="http://developer.android.com/reference/android/app/ListActivity.html" target="_blank">ListActivity</a></code> に変更します。またpublic void Create以下をリファレンスのコードと差し替えます。そして足りないimport文などを追加したのが下記コードになります。</p>
<pre class="brush: java;highlight:[13,17,18,28]">package localhost.helloview;

import android.app.ListActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

public class HelloListView extends ListActivity {
    /** Called when the activity is first created. */
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setListAdapter(
			new ArrayAdapter&lt;String&gt;(
				this,
				R.layout.list_item,
				COUNTRIES
			)
		);

		ListView lv = getListView();
		lv.setTextFilterEnabled(true);

		lv.setOnItemClickListener(new OnItemClickListener() {
		    public void onItemClick(
			    AdapterView&lt;?&gt; parent,
			    View view,
			    int position,
			    long id
			){
		       // When clicked, show a toast with the TextView text
		       Toast.makeText(
		    	   getApplicationContext(),
		    	   ((TextView) view).getText(),
		           Toast.LENGTH_SHORT
		       ).show();
		    }
		});
	}

    static final String[] COUNTRIES = new String[] {
        "Afghanistan", "Albania", "Algeria", "American Samoa",
        "Andorra","Angola", "Anguilla", "Antarctica",
        "Antigua and Barbuda", "Argentina",
    };
}</pre>
<div style="border: 1px solid #c0c0c0; padding: 10px; margin-top: 20px;">
<p>Notice that this does not load a layout file for the Activity (which you usually do with <code><a href="http://developer.android.com/reference/android/app/Activity.html#setContentView%28int%29" target="_blank">setContentView(int)</a></code>). Instead, <code><a href="http://developer.android.com/reference/android/app/ListActivity.html#setListAdapter%28android.widget.ListAdapter%29" target="_blank">setListAdapter(ListAdapter)</a></code> automatically adds a <code><a href="http://developer.android.com/reference/android/widget/ListView.html" target="_blank">ListView</a></code> to fill the entire screen of the <code><a href="http://developer.android.com/reference/android/app/ListActivity.html" target="_blank">ListActivity</a></code>. This method takes an <code><a href="http://developer.android.com/reference/android/widget/ArrayAdapter.html" target="_blank">ArrayAdapter</a></code>, which manages the array of list items that will be placed into the <code><a href="http://developer.android.com/reference/android/widget/ListView.html" target="_blank">ListView</a></code>. The <code><a href="http://developer.android.com/reference/android/widget/ArrayAdapter.html" target="_blank">ArrayAdapter</a></code> constructor takes the application <code><a href="http://developer.android.com/reference/android/content/Context.html" target="_blank">Context</a></code>, the layout description for each list item (created in the previous step), and a <code><a href="http://developer.android.com/reference/java/util/List.html" target="_blank">List</a></code> of objects to insert in the <code><a href="http://developer.android.com/reference/android/widget/ListView.html" target="_blank">ListView</a></code> (defined next).</p>
<p>The <code><a href="http://developer.android.com/reference/android/widget/AbsListView.html#setTextFilterEnabled%28boolean%29" target="_blank">setTextFilterEnabled(boolean)</a></code> method turns on text filtering for the <code><a href="http://developer.android.com/reference/android/widget/ListView.html" target="_blank">ListView</a></code>, so that when the user begins typing, the list will be filtered.</p>
<p>The <code><a href="http://developer.android.com/reference/android/widget/AdapterView.html#setOnItemClickListener%28android.widget.AdapterView.OnItemClickListener%29" target="_blank">setOnItemClickListener(OnItemClickListener)</a></code> method defines the on-click listener for each item. When an item in the <code><a href="http://developer.android.com/reference/android/widget/ListView.html" target="_blank">ListView</a></code> is clicked, the <code><a href="http://developer.android.com/reference/android/widget/AdapterView.OnItemClickListener.html#onItemClick%28android.widget.AdapterView%3C?%3E,%20android.view.View,%20int,%20long%29" target="_blank">onItemClick()</a></code> method is called and a <code><a href="http://developer.android.com/reference/android/widget/Toast.html" target="_blank">Toast</a></code> message is displayed, using the text from the clicked item.</p>
</div>
<p>[訳]<br />
ここではアクティビティでレイアウトファイルを読み込んでいないことに注目してください。（通常では<a href="http://developer.android.com/reference/android/app/Activity.html#setContentView%28int%29" target="_blank">setContentView(int)</a>メソッドを使って読み込みます。）その代わりに、<a href="http://developer.android.com/reference/android/app/ListActivity.html#setListAdapter%28android.widget.ListAdapter%29" target="_blank">setListAdapter(ListAdapter)</a>メソッドを使うことにより自動的に<a href="http://developer.android.com/reference/android/widget/ListView.html" target="_blank">ListView</a>が追加され<a href="http://developer.android.com/reference/android/app/ListActivity.html" target="_blank">ListActivity</a>の画面全体にリストが表示されます。このメソッドは<a href="http://developer.android.com/reference/android/widget/ArrayAdapter.html" target="_blank">ArrayAdapter</a>インスタンスをパラメータとして受け取り、<a href="http://developer.android.com/reference/android/widget/ListView.html" target="_blank">ListView</a>内で配置する項目の配列を管理します。<a href="http://developer.android.com/reference/android/widget/ArrayAdapter.html" target="_blank">ArrayAdapter</a>インスタンス生成にはコンストラクタとしてアプリケーションの<a href="http://developer.android.com/reference/android/content/Context.html" target="_blank">Context</a>、各リストアイテムの為のレイアウト記述（前ステップで作成した）、そして<a href="http://developer.android.com/reference/android/widget/ListView.html" target="_blank">ListView</a>に挿入するオブジェクトの<a href="http://developer.android.com/reference/java/util/List.html" target="_blank">List</a>（次のステップで定義します）をパラメータとして渡します。</p>
<p><a href="http://developer.android.com/reference/android/widget/AbsListView.html#setTextFilterEnabled%28boolean%29" target="_blank">setTextFilterEnabled(boolean)</a>メソッドは<a href="http://developer.android.com/reference/android/widget/ListView.html" target="_blank">ListView</a>に対してテキストフィルタリングをつけます。それによりユーザがタイプし始めるときにリストがフィルタされます。</p>
<p><a href="http://developer.android.com/reference/android/widget/AdapterView.html#setOnItemClickListener%28android.widget.AdapterView.OnItemClickListener%29" target="_blank">setOnItemClickListener(OnItemClickListener)</a>メソッドは各項目に対してon-clickリスナーを定義します。<a href="http://developer.android.com/reference/android/widget/ListView.html" target="_blank">ListView</a>の項目がクリックされたときに<a href="http://developer.android.com/reference/android/widget/AdapterView.OnItemClickListener.html#onItemClick%28android.widget.AdapterView%3C?%3E,%20android.view.View,%20int,%20long%29" target="_blank">onItemClick()</a>メソッドが呼ばれ、クリックされた項目からテキストを取得して<a href="http://developer.android.com/reference/android/widget/Toast.html" target="_blank">Toast</a>メッセージを表示します。</p>
<div style="margin-top: 50px;">[補足]</div>
<pre class="brush: java;first-line: 18">setListAdapter(
    new ArrayAdapter&lt;String&gt;(
        this,
        R.layout.list_item,
        COUNTRIES
    )
);</pre>
<p>ビューと表示するデータのやりとりにAdapter(アダプタ）を通しています。アダプタという言葉はよく耳にしますが、異なる規格や形状の差異を吸収す る中間装置（処理）の総称です。ArrayAdapterはデータリソースを加工して表示する形にしListViewに渡します。このようにアダプタが中間に入ってくれることでデータリソースが配列であれリストであれ違いはアダプタが吸収するのでビューは表示に専念することができます。</p>
<p><img class="aligncenter size-full wp-image-2164" style="margin-top: 20px; margin-bottom: 20px;" title="android110" src="http://memories.zal.jp/WP/wp-content/uploads/2011/08/android110.jpg" alt="" width="446" height="145" /></p>
<p style="margin-bottom: 30px;">ArrayAdapterは第2引数で各項目のデザイン情報を、第3引数でデータリソースを受け取ってます。上記の「レイアウトファイルの作成」でlist_item.xmlを作成しましたが、ここでのレイアウト情報はデータリソースの各項目に対してのもので全体に対してのものでないようです。ArrayAdapterで加工したデータをListViewに渡すわけですが、今回はレイアウトファイルを読み込む代わりにsetListAdapterアダプタを使っています。setListAdapterは自動的にListViewを作成するのでsetListAdapterにArrayAdapterを渡すことでListViewに渡すのと同様の効果になっています。</p>
<pre class="brush: java;first-line: 28">lv.setOnItemClickListener(new OnItemClickListener() {</pre>
<p>ListViewの項目がクリックされたときに実行されるコールバックを登録します。今回はToastクラスを使って国名を表示するだけです。トーストとは一定の時間表示するポップアップウィンドウのことです。</p>
<div class="title-blue-line-middle" style="margin-top: 50px;">AVDによる実行</div>
<p>AVDによるアプリケーションの実行については「<a href="http://memories.zal.jp/WP/20110516_2073.html#app_excute" target="_blank">AVDでアプリケーションを実行する</a>」の記事で詳しく書きました。参考にしてください。</p>
<p>実行結果をみてみます。次のような画面が表示されました。</p>
<p><img class="aligncenter size-full wp-image-2165" title="android111" src="http://memories.zal.jp/WP/wp-content/uploads/2011/08/android111.jpg" alt="" width="500" height="460" /></p>
]]></content:encoded>
			<wfw:commentRss>http://memories.zal.jp/WP/blog/20110817_2162.html/feed</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
	</channel>
</rss>

