marunomaruno-memo

marunomaruno-memo

[Android] コンテナ (2) スクロール表示 - ScrollView、HorizontalScrollView

2012年03月26日 | Android
[Android] コンテナ (2) スクロール表示 - ScrollView、HorizontalScrollView
================================================================================

ScrollView は、そのコンテンツのスクロール機能を提供するコンテナ。画面に入りきれ
ないと思われるウィジェットを ScrollView で囲むことで、既存のレイアウトをそのまま
使うことができる。

使い方としては以下のとおり。
    <ScrollView>
        他のウィジェット
    </ScrollView>


ScrollView は、縦スクロール。HorizontalScrollView は横スクロールが可能になる。
縦と横の両方を可能にするためには、ScrollView と HorizontalScrollView とを組み合
わせればよい。すなわち、次のような形になる。
    <HorizontalScrollView>
        <ScrollView>
            他のウィジェット
        </ScrollView>
    </HorizontalScrollView>


▲ レイアウト

同じレイアウトに対して、つぎの 3 つのパターンを表示。

    ScrollView
    HorizontalScrollView
    ScrollView と HorizontalScrollView の組合わせ

レイアウトは、TableLayout01 のサンプル。
したがって、拡大していくと、それぞれが縦スクロール、横スクロール、縦横スクロール
ができる。

わかりやすくするために、ScrollView 要素に囲まれているウィジェットは、table.xml 
をインクルードしている。

□ res/layout/main.xml
---
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="vertical" >
    
    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="ScrollView"
        android:textAppearance="?android:attr/textAppearanceLarge" />
    
    <ScrollView
        android:id="@+id/scrollView1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_weight="1" >

        <include android:id="@+id/table0" layout="@layout/table" />
    </ScrollView>

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="HorizontalScrollView"
        android:textAppearance="?android:attr/textAppearanceLarge" />
        
    <HorizontalScrollView
        android:id="@+id/horizontalScrollView1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_weight="1" >

        <include android:id="@+id/table1" layout="@layout/table" />
    </HorizontalScrollView>

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="HorizontalScrollView + ScrollView"
        android:textAppearance="?android:attr/textAppearanceLarge" />
        
    <HorizontalScrollView
        android:id="@+id/horizontalScrollView2"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_weight="1" 
        android:scrollbars="none">

        <ScrollView
            android:id="@+id/scrollView2"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content" 
            android:scrollbars="none">

            <include android:id="@+id/table2" layout="@layout/table" />
        </ScrollView>
    </HorizontalScrollView>

</LinearLayout>
---


□ ScrollView クラス

java.lang.Object
   +   android.view.View
        +   android.view.ViewGroup
             +   android.widget.FrameLayout
                  +   android.widget.ScrollView

ScrollView は、そのコンテンツの縦スクロール機能を提供するコンテナ。


XML 属性(属性名の前に、名前空間プレフィックス android: がつく)
---
fillViewport  子のウィジェットが小さい場合でも、このビューの高さ分の領域をとる
---

setFillViewport(boolean) メソッドにより、属性値を動的に変更できる。


□ HorizontalScrollView

java.lang.Object
   +   android.view.View
        +   android.view.ViewGroup
             +   android.widget.FrameLayout
                  +   android.widget.HorizontalScrollView

HorizontalScrollView は、そのコンテンツの横スクロール機能を提供するコンテナ。


XML 属性(属性名の前に、名前空間プレフィックス android: がつく)
---
fillViewport  子のウィジェットが小さい場合でも、このビューの幅分の領域をとる
---

setFillViewport(boolean) メソッドにより、属性値を動的に変更できる。


・スクロールバーの表示

android:scrollbars 属性は、スクロールバーを表示するかしないかを指定する。
つぎの値が指定できる。
    none          スクロールが必要になっても表示しない
    horizontal    横スクロールが必要なときに横バーを表示
    vertical      縦スクロールが必要なときに縦バーを表示

なお、ScrollViewで、実際にスクロールバーが表示されるのは、スクロールが必要なとき
で、android:scrollbars="vertical" と指定しても、最初からスクロールバーが表示され
るわけではない。表示させたくないときは値 "none" を指定する。


□ res/layout/table.xml

※ TableLayout01 プロジェクトの res/layout/main.xml と同じ。


▲ アクティビティ

ボタンがクリックされたら、その状態によって、ボタンの幅と高さを倍にするか半分にす
る。

□ ScrollView01Activity.java

※ クラス名が上記の名前になっているだけで、コードは LinearLayout01Activity.java と同じ。


■ 実例

サンプルのプロジェクトは、以下の記事を参照。
    SystemOut01 プロジェクト
    標準出力 - あて先に画面を追加する, 2011-12-22
    http://blog.goo.ne.jp/marunomarunogoo/d/20111222

System.out を TextView に割り当て、いかにもコンソールに出力するように、表示部分
がスクロールするようにしているサンプルである。


▲ レイアウト

レイアウトだけ再掲載する。

□ res/layout/main.xml

---
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="vertical" >

    <ScrollView
        android:id="@+id/sysoutScrollView"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content" >    <!-- (1) -->

        <TextView
            android:id="@+id/sysout"
            android:layout_width="fill_parent"
            android:layout_height="wrap_content" />    <!-- (2) -->
    </ScrollView>

</LinearLayout>
---

ScrollView 要素の下に TextView 要素。この TextView が画面いっぱいになったら、ス
クロール・バーが表示される。


■ 自動スクロールダウン

ScrollView を使っただけでは、自動的にスクロールダウンしない。自動的にスクロール
ダウンさせるのであれば、以下のようなスレッドを作り、ポストする。

上記の例であれば、
        TextView view = (TextView) findViewById(R.id.sysout);
としたときに、

    ((View) view.getParent()).post(new ScrollDown());

で、スクロール・ダウンさせるスレッドを設定する。

スクロール・ダウンさせるスレッドは、以下のように作成する。
なお、view は、インスタンス・フィールドか、final ローカル変数として定義してある
ものとする。

---
    /**
     * スクロールダウンさせるスレッドのクラス
     * @author marunomaruno
     */
    private class ScrollDown implements Runnable { // (8)
        public void run() {
            ((ScrollView) view.getParent()).fullScroll(View.FOCUS_DOWN); // (9)
        }
    }
---

                                                                            以上


[Android] レイアウト (5) レイアウトの組込み - include

2012年03月24日 | Android
[Android] レイアウト (5) レイアウトの組込み - include
================================================================================

他のレイアウトの XML ファイルを、自身の中に組み込むことができる。
このためには、
    <include layout="@layout/XMLファイル名" />
要素を使う。


・属性

layout
    レイアウトリソース。 必須。レイアウトリソースに対する参照。

android:id
    リソース ID。インクルードされたレイアウトのルート要素のビューで指定された ID
 はこれで上書きされる。

android:layout_height, android:layout_width
    ディメンションまたはキーワード。インクルードされたレイアウトのルート要素のビ
ューで指定された高さ、幅はこれで上書きされる。 

インクルードされたレイアウトのルート要素でサポートされていれば、 <include> には
他のレイアウト属性を含めることが可能で、それらはルート要素で定義されたものを上書
きする。


□ 参考
ソフトウェア技術ドキュメントを勝手に翻訳
Android 開発ガイド > フレームワークトピック > 7. アプリケーションリソース > 
7.5 リソースタイプ > 
7.5.4 レイアウトリソース 
http://www.techdoctranslator.com/android/guide/resources/available-resources/layout-resource


▲ レイアウト

3x3 のテーブルのレイアウトを定義する。このとき、1 行分を定義する row.xml、1 項目
分を定義する item.xml を用意し、include 要素で引っ張ってきている。

    main.xml    TableLayout 要素でテーブルを定義。3 つの row.xml を参照している
    row.xml     TableRow 要素で行を定義。3 つの item.xml を参照している
    item.xml    ToggleButton 要素

□ res/layout/main.xml
---
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="vertical" >

    <TableLayout
        android:id="@+id/tableLayout1"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:padding="5dip"
        android:weightSum="1" >

        <include android:id="@+id/row0" layout="@layout/row" />
        <include android:id="@+id/row1" layout="@layout/row" />
        <include android:id="@+id/row2" layout="@layout/row" />
        
    </TableLayout>

</LinearLayout>
---


1 行分の定義

□ res/layout/row.xml
---
<?xml version="1.0" encoding="utf-8"?>
<TableRow xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content" >

    <include android:id="@+id/button0" layout="@layout/item" />
    <include android:id="@+id/button1" layout="@layout/item" />
    <include android:id="@+id/button2" layout="@layout/item" />
    
</TableRow>
---


1 項目分の定義

□ res/layout/item.xml
---
<?xml version="1.0" encoding="utf-8"?>
<ToggleButton xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:onClick="onClick"
    android:textAppearance="?android:attr/textAppearanceLarge"
 />
---


▲ アクティビティ

ボタンがクリックされたら、その状態によって、ボタンの幅と高さを倍にするか半分にす
る。

コードは LinearLayout01Activity.java と同じであるが、末端のウィジェットを区別す
るのに、getId() メソッドを使って、リソース ID をログに出す部分が追加になっている。


□ IncludeLayout01Activity.java
---
package jp.marunomaruno.android.includelayout;

import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.ToggleButton;
import jp.marunomaruno.android.includelayout.R;

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

    public void onClick(View view) {
        ToggleButton button = (ToggleButton) view;
        if (button.isChecked()) {
            button.setWidth(button.getWidth() * 2);
            button.setHeight(button.getHeight() * 2);

        } else {
            button.setWidth(button.getWidth() / 2);
            button.setHeight(button.getHeight() / 2);

        }

        System.out.printf("parent id = %x, id = %x", ((View) view.getParent())
                .getId(), view.getId());    // (1)
        System.out.println();
    }
}
---

(1) クリックしたビューと、その親ビューのリソース ID を表示

オブジェクトの特定のために、自身のリソース ID と、親のビュー(include 要素につけ
られた ID)のリソース ID をログに出力する。
R クラスの表現とあわせるために、16 進表記している。

    System.out.printf("parent id = %x, id = %x", ((View) view.getParent())
            .getId(), view.getId());    // (1)


View クラスのメソッド
---
int               getId()      リソース ID を取得する
final ViewParent  getParent()  親ビューを取得する
---


□ ViewParent インターフェース

親ビューになる可能性のあるビューのインターフェース。
次のビューのクラスがこのインターフェースを実装している。
    AbsListView
    AbsSpinner
    AbsoluteLayout
    AdapterView<T?extends?Adapter>
    AdapterViewAnimator
    AdapterViewFlipper
    AppWidgetHostView
    CalendarView
    DatePicker
    DialerFilter
    ExpandableListView
    FragmentBreadCrumbs
    FrameLayout
    Gallery
    GestureOverlayView
    GridLayout
    GridView
    HorizontalScrollView
    ImageSwitcher
    LinearLayout
    ListView
    MediaController
    NumberPicker
    RadioGroup
    RelativeLayout
    ScrollView
    SearchView
    SlidingDrawer
    Spinner
    StackView
    TabHost
    TabWidget
    TableLayout
    TableRow
    TextSwitcher
    TimePicker
    TwoLineListItem
    ViewAnimator
    ViewFlipper
    ViewGroup
    ViewSwitcher
    WebView
    ZoomControls

ViewParent インターフェースには、getId() メソッドがないので、これを使ってリソー
ス ID を取得するためには、View にキャストして使う必要がある。


                                                                            以上


[Android] レイアウト (4) RelativeLayout レイアウト

2012年03月23日 | Android
[Android] レイアウト (4) RelativeLayout レイアウト
================================================================================

他のウィジェットの横や下にどの程度離れて配置するか、を示すルールベース・モデルの
レイアウト。
他のウィジェットとの相対位置を基にして、自分の位置を決める。
他のウィジェットは、自分の隣りである必要はなく、離れていても OK。
相対位置は、RelativeLayout に組み込まれているいくつかの属性を利用することで指定
する。

この RelativeLayout を使うと、ウィジェットの上にウィジェットを重ねられる。


XML 属性(属性名の前に、名前空間プレフィックス android: がつく)
---
android:gravity        setGravity(int)        ウィジェットの配置方法
android:ignoreGravity  setIgnoreGravity(int)  gravityで 指定した配置方法の影響を
受けない Widget を指定
---


・コンテナを基準とする位置

これらの値は論理値(true/false)。

android:layout_alignParentBottom  ウィジェットの下辺とコンテナの下辺をそろえる
android:layout_alignParentLeft    ウィジェットの左辺とコンテナの左辺をそろえる
android:layout_alignParentRight   ウィジェットの右辺とコンテナの右辺をそろえる
android:layout_alignParentTop     ウィジェットの上辺とコンテナの上辺をそろえる

android:layout_centerHorizontal   ウィジェットをコンテナの中央に水平に配置
android:layout_centerVertical     ウィジェットをコンテナの中央に垂直に配置
android:layout_centerInParent     ウィジェットをコンテナの中央に水平・垂直に配置


・他のウィジェットを基準とする位置

他のウィジェットは、@id/リソースID で参照する。

android:layout_above        指定されたビューの上辺にこのビューを配置
android:layout_below        指定されたビューの下辺にこのビューを配置
android:layout_toLeftOf     指定されたビューの左辺にこのビューを配置
android:layout_toRightOf    指定されたビューの右辺にこのビューを配置

android:layout_alignBottom  指定されたビューの下辺にこのビューの下辺をそろえる
android:layout_alignLeft    指定されたビューの左辺にこのビューの左辺辺をそろえる
android:layout_alignRight   指定されたビューの右辺にこのビューの右辺をそろえる
android:layout_alignTop     指定されたビューの上辺にこのビューの上辺をそろえる


マージンについては、ViewGroup.MarginLayoutParams を参照。
レイアウト (1) レイアウトの概要
http://blog.goo.ne.jp/marunomarunogoo/d/20120320


▲ レイアウト

一部のウィジェットが重なって表示される。

□ res/layout/main.xml
---
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="vertical" >

    <RelativeLayout
        android:id="@+id/relativeLayout1"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:orientation="vertical"
        android:padding="5dip"
        android:weightSum="1" >

        <ToggleButton
            android:id="@+id/button1"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_alignParentLeft="true"
            android:layout_alignParentTop="true"
            android:onClick="onClick"
            android:textAppearance="?android:attr/textAppearanceLarge"
            android:textOff="1¥nParentLeft¥nParentTop"
            android:textOn="1¥nParentLeft¥nParentTop" />

        <ToggleButton
            android:id="@+id/button2"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_alignLeft="@id/button1"
            android:layout_below="@id/button1"
            android:onClick="onClick"
            android:textAppearance="?android:attr/textAppearanceLarge"
            android:textOff="2¥nbelow=1"
            android:textOn="2¥nbelow=1" />

        <ToggleButton
            android:id="@+id/button3"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_alignTop="@id/button2"
            android:layout_below="@id/button2"
            android:layout_toRightOf="@id/button2"
            android:onClick="onClick"
            android:textAppearance="?android:attr/textAppearanceLarge"
            android:textOff="3¥nalignTop=2¥nbelow=2¥ntoRightOf=2"
            android:textOn="3¥nalignTop=2¥nbelow=2¥ntoRightOf=2" />

        <ToggleButton
            android:id="@+id/button4"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_alignRight="@id/button3"
            android:layout_below="@id/button3"
            android:onClick="onClick"
            android:textAppearance="?android:attr/textAppearanceLarge"
            android:textOff="4¥nalignRight=3¥nbelow=3"
            android:textOn="4¥nalignRight=3¥nbelow=3" />

        <ToggleButton
            android:id="@+id/button5"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_alignParentRight="true"
            android:layout_below="@id/button2"
            android:onClick="onClick"
            android:textAppearance="?android:attr/textAppearanceLarge"
            android:textOff="5¥nParentRight¥nbelow=2"
            android:textOn="5¥nParentRight¥nbelow=2" />
        
        <ToggleButton
            android:id="@+id/button6"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_below="@id/button2"
            android:onClick="onClick"
            android:textAppearance="?android:attr/textAppearanceLarge"
            android:textOff="6¥nbelow=2"
            android:textOn="6¥nbelow=2" />
        
        </RelativeLayout>

</LinearLayout>
---


□ 表示
---
1
ParentLeft
ParenTop

2               3
below=1         alignTop=2
                below=2
6               toRightOf=2              5
below=2                                  ParentRight
                4                        bwlow=2
                alignRight=3
                below=3
---


設定値のまとめ
------------------------- --- --- --- --- --- --- 
                           1   2   3   4   5   6
------------------------- --- --- --- --- --- --- 
layout_alignParentBottom 
layout_alignParentLeft     x
layout_alignParentRight                x
layout_alignParentTop      x      
------------------------- --- --- --- --- --- --- 
layout_above             
layout_below                   1   2   3   2   2
layout_toLeftOf          
layout_toRightOf                   2
------------------------- --- --- --- --- --- --- 
layout_alignBottom       
layout_alignLeft         
layout_alignRight                      3
layout_alignTop                    2
------------------------- --- --- --- --- --- --- 

[1] は、親レイアウトの左端と上端に合わせる。

[2] は、[1] の下端に、自身の上端を合わせる。

[3] は、layout_below="2" と layout_alignTop="2" が指定されているが、[2] の上端と
自身の上端が合っている。また、layout_toRightOf="2" なので、[2] の右端が自身の左
端と合っている。

[4] は、[3] の下端に、自身の上端を合わせ、左端を合わせている。

[5] は、[2] の下端に、自身の上端を合わせ、親レイアウトの右端と自身の右端を合わせ
ている。

[6] は、[2] の下端に、自身の上端を合わせる。


□ RelativeLayout クラス

java.lang.Object
   +   android.view.View
        +   android.view.ViewGroup
             +   android.widget.RelativeLayout

相対レイアウトを定義するクラス。


XML 属性(属性名の前に、名前空間プレフィックス android: がつく)
---
android:gravity
android:ignoreGravity
---

それぞれ、以下のメソッドで動的に変更できる。
    setGravity(int)
    setIgnoreGravity(int)


□ RelativeLayout.LayoutParams クラス

java.lang.Object
   +   android.view.ViewGroup.LayoutParams
        +   android.view.ViewGroup.MarginLayoutParams
             +   android.widget.RelativeLayout.LayoutParams

相対レイアウトのパラメーターを定義するクラス。


XML 属性(属性名の前に、名前空間プレフィックス android: がつく)
---
android:layout_above
android:layout_alignBaseline
android:layout_alignBottom
android:layout_alignLeft
android:layout_alignParentBottom
android:layout_alignParentLeft
android:layout_alignParentRight
android:layout_alignParentTop
android:layout_alignRight
android:layout_alignTop
android:layout_alignWithParentIfMissing
android:layout_below
android:layout_centerHorizontal
android:layout_centerInParent
android:layout_centerVertical
android:layout_toLeftOf
android:layout_toRightOf
---

それぞれに対するメソッドはない。説明は上記を参照。


▲ アクティビティ

ボタンがクリックされたら、その状態によって、ボタンの幅と高さを倍にするか半分にす
る。

□ RelativeLayout01Activity.java

※ クラス名が上記の名前になっているだけで、コードは LinearLayout01Activity.java 
と同じ。

                                                                            以上


[Android] レイアウト (3) テーブル・レイアウト

2012年03月22日 | Android
[Android] レイアウト (3) テーブル・レイアウト
================================================================================

テーブル形式でウィジェットを配置するグリッド・モデルのレイアウトである。
TableLayout は TableRow と連動する。TableRow は、テーブルの行を規定する。

使い方としては、以下のとおり。

<TableLayout>
    <TableRow>
        ウィジェット
        ウィジェット
            ...
    </TableRow>

    <TableRow>
        ウィジェット
        ウィジェット
            ...
    </TableRow>

        ...
</TableLayout>


・行にセルを配置する

行の宣言は、TableRow で行う。
列数は Android が決定する。

android:layout_span 属性で、ウィジェットを複数の列に広げることができる。


・TableLayout の子要素

直接の子は TableRow 要素だけである。
ただし、TableRow 要素以外にも行と行の間に他のウィジェットを配置できる。その場合
は、横方向の LinearLayout と同様に振る舞う。


・伸縮とたたみ込み

android:stretchColumns 属性で、ここに指定した列は、行の空いているスペースいっぱ
いに広がる。この属性の値は単一の列番号またはコンマ区切りの列番号のリストで指定す
る。列番号は左の列から 0 から振られる。
実行時に、TableLayout.setColumnsStretchable() メソッドで制御できる。

android:shrinkColumns 属性で、ここに指定した列は、コンテンツを折り返して表示する。
値の指定は、android:stretchColumns 属性と同じ。
実行時に、TableLayout.setColumnsShrinkale() メソッドで制御できる。

android:collapseColumns 属性で、ここに指定した列は、最初はたたみ込まれた状態にな
る。これは最初は表示されない列となる。表示するには、TableLayout
.setColumnsCollapsed() メソッドを呼び出すことで表示される。


▲ レイアウト

□ res/layout/main.xml
---
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="vertical" >

    <TableLayout
        android:id="@+id/tableLayout1"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:padding="5dip"
        android:weightSum="1" >

        <TableRow
            android:id="@+id/tableRow0"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content" >

            <ToggleButton
                android:id="@+id/button00"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:onClick="onClick"
                android:textAppearance="?android:attr/textAppearanceLarge"
                android:textOff="[0][0]"
                android:textOn="[0][0]" />

            <ToggleButton
                android:id="@+id/button01"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:onClick="onClick"
                android:textAppearance="?android:attr/textAppearanceLarge"
                android:textOff="[0][1]"
                android:textOn="[0][1]" />

            <ToggleButton
                android:id="@+id/button02"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:onClick="onClick"
                android:textAppearance="?android:attr/textAppearanceLarge"
                android:textOff="[0][2]"
                android:textOn="[0][2]" />
        </TableRow>

        <TableRow
            android:id="@+id/tableRow1"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content" >

            <ToggleButton
                android:id="@+id/button10"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:onClick="onClick"
                android:textAppearance="?android:attr/textAppearanceLarge"
                android:textOff="[1][0]"
                android:textOn="[1][0]" />

            <ToggleButton
                android:id="@+id/button11"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:onClick="onClick"
                android:textAppearance="?android:attr/textAppearanceLarge"
                android:textOff="[1][1]"
                android:textOn="[1][1]" />

            <ToggleButton
                android:id="@+id/button12"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:onClick="onClick"
                android:textAppearance="?android:attr/textAppearanceLarge"
                android:textOff="[1][2]"
                android:textOn="[1][2]" />
        </TableRow>

        <TableRow
            android:id="@+id/tableRow2"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content" >

            <ToggleButton
                android:id="@+id/button20"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:layout_span="2"
                android:onClick="onClick"
                android:textAppearance="?android:attr/textAppearanceLarge"
                android:textOff="[2][0]"
                android:textOn="[2][0]" />

            <ToggleButton
                android:id="@+id/button22"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:onClick="onClick"
                android:textAppearance="?android:attr/textAppearanceLarge"
                android:textOff="[2][2]"
                android:textOn="[2][2]" />
        </TableRow>
    </TableLayout>

</LinearLayout>
---

TableLayout の場合は、なるべく幅に入るように調整されるようだ。

TableLayout の属性は、そのスーパークラスである LinearLayout と同じ。


□ TableLayout クラス

java.lang.Object
   +    android.view.View
        +    android.view.ViewGroup
             +    android.widget.LinearLayout
                  +    android.widget.TableLayout

テーブル形式のレイアウトを定義するクラス。
この子要素として TableRow を使うことで、行を定義する。

XML 属性としては、上記の「伸縮とたたみ込み」に関する属性がある。


XML 属性(属性名の前に、名前空間プレフィックス android: がつく)
---
android:collapseColumns
android:shrinkColumns
android:stretchColumns
---

それぞれ、つぎのメソッドで動的に変更できる。
    setColumnCollapsed(int,boolean)
    setShrinkAllColumns(boolean)
    setStretchAllColumns(boolean)


□ TableRow クラス

java.lang.Object
   +    android.view.View
        +    android.view.ViewGroup
             +    android.widget.LinearLayout
                  +    android.widget.TableRow

テーブルの行を定義するクラス。
この子要素としてウィジェットを指定すると、それがテーブルの項目として定義される。

このクラスには、とくに XML 属性はない。行の属性としては、内部クラスの TableRow
.LayoutParams クラス で定義している。


□ TableRow.LayoutParams クラス

java.lang.Object
   +    android.view.ViewGroup.LayoutParams
        +    android.view.ViewGroup.MarginLayoutParams
             +    android.widget.LinearLayout.LayoutParams
                  +    android.widget.TableRow.LayoutParams

テーブルの行の属性を定義するクラス。


XML 属性(属性名の前に、名前空間プレフィックス android: がつく)
---
layout_column    ビューの列数
layout_span      結合する列数
---

この属性に関するメソッドはない。


---
★?
TableLayout では、HTML の table 要素のような行の結合(rowspan)はできないようだ。
---


□ 表示
---
00        01        02

10        11        12

20                  22
---


▲ アクティビティ

□ TableLayout01Activity.java

※ クラス名が上記の名前になっているだけで、コードは LinearLayout01Activity.java と同じ。

                                                                            以上


[Android] レイアウト (2) LinearLayout レイアウト

2012年03月21日 | Android
[Android] レイアウト (2) LinearLayout レイアウト
================================================================================

LinearLayout は、ウィジェットを縦または横に並べて配置するボックス・モデルのレイア
ウト。
つぎの属性によって配置のしかたを決める。
    方向
    塗りつぶしモデル
    配置
    パディング


・方向

縦方向にウィジェットを並べるか、横方向に並べるかを示す。
    android:orientation="vertical" または "horizontal"

なにも記述しないときは横方向。


・塗りつぶしモデル

ウィジェットを並べたときに、ウィジェットの大きさをどうするかを示す。

横方向、縦方向に関して、それぞれ
        android:layout_width
        android:layout_height
属性で指定する。


・比率

そのウィジェットに割りあてられる領域の割合を示す。
    android:layout_weight


・配置

そのウィジェットの配置(左寄せ、センタリング、右寄せなど)を示す。
    android:gravity

---
★?
LinearLayout の API 上では android:layout_gravity だが、実際には android:gravity
 で設定するようだ。layout_gravity だとうまく配置できない。
たとえば、android:gravity="center" ならセンタリングしてくれるが、
android:layout_gravity="center" だと左寄せのまま。
---


指定できる値
---
top    
bottom  
left   
right   
center_vertical  
fill_vertical    
center_horizontal
fill_horizontal     
center  
fill    
clip_vertical
clip_horizontal
start   
end    
---


・パディング

ウィジェット間の余白を指定する。何も指定しなければ余白なし。
android:padding 属性をつけることで、上下左右にも余白をつけることができる。
また、上下左右個別につけることもできる。


属性
---
android:padding        上下左右のパディングをピクセル単位で設定
android:paddingBottom  下方向のパディングをピクセル単位で設定
android:paddingLeft    左方向のパディングをピクセル単位で設定
android:paddingRight   右方向のパディングをピクセル単位で設定
android:paddingTop     上方向のパディングをピクセル単位で設定
---

なお、つぎのメソッドでパディングを動的に設定できる。
    setPadding(int,int,int,int)


▲ レイアウト

テーブル形式にウィジェットを並べた。ウィジェットは、ToggleButton で、ON になると、
サイズが縦方向横方向それぞれ動的に 2 倍になる。OFF になればもとに戻る。
ただし、レイアウトによっては、見た目は 2 倍にならないときもある。

□ res/layout/main.xml
---
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="vertical" >

    <LinearLayout
        android:id="@+id/tableLayout1"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:padding="5dip" >

        <ToggleButton
            android:id="@+id/button00"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:onClick="onClick"
            android:textAppearance="?android:attr/textAppearanceMedium"
            android:textOff="[0][0]¥nww-"
            android:textOn="[0][0]¥nww-" />

        <ToggleButton
            android:id="@+id/button01"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:onClick="onClick"
            android:textAppearance="?android:attr/textAppearanceMedium"
            android:textOff="[0][1]¥nww-"
            android:textOn="[0][1]¥nww-" />

        <ToggleButton
            android:id="@+id/button02"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:onClick="onClick"
            android:textAppearance="?android:attr/textAppearanceMedium"
            android:textOff="[0][2]¥nmw-"
            android:textOn="[0][2]¥nmw-" />
    </LinearLayout>

    <LinearLayout
        android:id="@+id/tableLayout1"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:padding="5dip" >

            <ToggleButton
            android:id="@+id/button10"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:onClick="onClick"
            android:textAppearance="?android:attr/textAppearanceMedium"
            android:textOff="[1][0]¥nmw-"
            android:textOn="[1][0]¥nmw-" />

        <ToggleButton
            android:id="@+id/button11"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:onClick="onClick"
            android:textAppearance="?android:attr/textAppearanceMedium"
            android:textOff="[1][1]¥nww-"
            android:textOn="[1][1]¥nww-" />
    </LinearLayout>

    <LinearLayout
        android:id="@+id/tableLayout2"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:padding="5dip" >

        <ToggleButton
            android:id="@+id/button20"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_span="2"
            android:layout_weight="1"
            android:onClick="onClick"
            android:textAppearance="?android:attr/textAppearanceMedium"
            android:textOff="[2][0]¥nww1"
            android:textOn="[2][0]¥nww1" />

        <ToggleButton
            android:id="@+id/button21"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_span="2"
            android:layout_weight="1"
            android:onClick="onClick"
            android:textAppearance="?android:attr/textAppearanceMedium"
            android:textOff="[2][1]¥nww1"
            android:textOn="[2][1]¥nww1" />

        <ToggleButton
            android:id="@+id/button22"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:onClick="onClick"
            android:textAppearance="?android:attr/textAppearanceMedium"
            android:textOff="[2][2]¥nww1"
            android:textOn="[2][2]¥nww1" />
    </LinearLayout>

    <LinearLayout
        android:id="@+id/tableLayout3"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:padding="5dip" >

        <ToggleButton
            android:id="@+id/button30"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_span="2"
            android:layout_weight="2"
            android:onClick="onClick"
            android:textAppearance="?android:attr/textAppearanceMedium"
            android:textOff="[3][0]¥nww2"
            android:textOn="[3][0]¥nww2" />

        <ToggleButton
            android:id="@+id/button32"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:onClick="onClick"
            android:textAppearance="?android:attr/textAppearanceMedium"
            android:textOff="[3][2]¥nww1"
            android:textOn="[3][2]¥nww1" />
    </LinearLayout>

    <LinearLayout
        android:id="@+id/tableLayout4"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:padding="5dip" >

        <ToggleButton
            android:id="@+id/button40"
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_span="2"
            android:layout_weight="2"
            android:onClick="onClick"
            android:textAppearance="?android:attr/textAppearanceMedium"
            android:textOff="[4][0]¥n0w2"
            android:textOn="[4][0]¥n0w2" />

        <ToggleButton
            android:id="@+id/button42"
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:onClick="onClick"
            android:textAppearance="?android:attr/textAppearanceMedium"
            android:textOff="[4][2]¥n0w1"
            android:textOn="[4][2]¥n0w1" />
    </LinearLayout>

    <LinearLayout
        android:id="@+id/tableLayout5"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:gravity="center"
        android:padding="5dip" >

        <ToggleButton
            android:id="@+id/button50"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_span="2"
            android:onClick="onClick"
            android:textAppearance="?android:attr/textAppearanceMedium"
            android:textOff="[5][0]¥nww-"
            android:textOn="[5][0]¥nww-" />
    </LinearLayout>

</LinearLayout>
---


□ LinearLayout.LayoutParams クラス

java.lang.Object
   +    android.view.ViewGroup.LayoutParams
        +    android.view.ViewGroup.MarginLayoutParams
             +    android.widget.LinearLayout.LayoutParams

LinearLayout で配置する場合のウィジェットに割り当てられる領域の割合などを設定す
る。

XML 属性(属性名の前に、名前空間プレフィックス android: がつく)
---
android:layout_gravity  ウィジェットの配置
android:layout_weight   そのウィジェットに割りあてられる領域の割合
---


□ android:layout_weight の使い方 (1) 

・android:layout_weight に "0" 以外の値を指定する。

・2 つの要素で、同じ 0 以外の値を指定すると領域が均等に二分

・ひとつ目で "1"、ふたつ目に "2" を指定すると、ふたつ目のウィジェットはひとつ目
の 2 倍の領域を使う


□ android:layout_weight の使い方 (2) 

割合に基づいてサイズを指定する。

水平レイアウトの場合

・レイアウト内のすべてのウィジェットで android:layout_width="0dp" とする

・レイアウト内のすべてのウィジェットで android:layout_weight の値を適切な割合に
する

・レイアウト内のすべてのウィジェットの android:layout_weight の値の合計が 100 に
なるようにする

実際には、合計が 100 にならなくても、全体の合計に対する割合で、領域の大きさを決
めてくれる。値も、整数値である必要はなく、実数値でもよい。


▲ アクティビティ

ボタンがクリックされたら、その状態によって、ボタンの幅と高さを倍にするか半分にす
る。

□ LinearLayout01Activity.java
---
package jp.marunomaruno.android.linearlayout;

import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.ToggleButton;
import jp.marunomaruno.android.linearlayout.R;

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

    public void onClick(View view) {
        ToggleButton button = (ToggleButton) view;
        if (button.isChecked()) {
            button.setWidth(button.getWidth() * 2);
            button.setHeight(button.getHeight() * 2);

        } else {
            button.setWidth(button.getWidth() / 2);
            button.setHeight(button.getHeight() / 2);

        }
    }
}
---

ボタンに表示される 3 ケタの記号は順番に、
    layout_width 値
    layout_height 値
    layout_weight 値
を意味し、数字はその値である。また、記号 w と m は、それぞれ
    w:    wrap_content
    m:    match_parent
を意味する。


□ 表示
---
00        01        02
ww-       ww-       mw-

10        11        12
mw-       ww-       mw-

20        21        22
ww1       ww1       ww1

30                  32
ww2                 ww1

40                  42
0w2                 0w1

          50
          ww-
---

[3x] と [4x] とでは、layout_width 属性に値が設定されているかどうかの違い。

                                                                            以上



[Android] レイアウト (1) レイアウトの概要

2012年03月20日 | Android
[Android] レイアウト (1) レイアウトの概要
================================================================================

Android では、4 種類のレイアウトがある。

LinearLayout    ウィジェットを縦または横に並べて配置(ボックス・モデル)
RelativeLayout  他のウィジェットとの相対位置を基にして自分を配置
                (ルールベース・モデル)
TableLayout     テーブル形式でウィジェットを配置(グリッド・モデル)
FrameLayout     ひとつのウィジェットを配置

参考
ソフトウェア技術ドキュメントを勝手に翻訳
Android 開発ガイド > フレームワークトピック > 6. ユーザインターフェイス 
                                                > 6.b 共通レイアウトオブジェクト
http://www.techdoctranslator.com/android/guide/ui/layout-objects


レイアウトは、ViewGroup と、ViewGroup.LayoutParams で特徴づけられる。
また、それぞれのレイアウトは、ViewGroup.LayoutParams から継承される 
xxx.LayoutParams がある。(xxx は、AbsListView、RelativeLayout、LinearLayout、
FrameLayout)
それぞれの継承関係は以下のとおり。

                                                  ================
                                                  AbsListView
                                             ---  .LayoutParams
                                             |    ----------------
                                             |    x
                                             |    y
                                             |    ================
                                             |
                                             |
=============        ===================     |    ================
ViewGroup            ViewGroup               |    RelativeLayout
.LayoutParms  <|---  .MarginLayoutParams  <|-+--  .LayoutParms
------------         -------------------     |    ----------------
height               marginBottom            |    above
weidth               marginLeft              |    below
============         marginRight             |    alignLeft
                     marginTop               |    alignRight
                     ===================     |    toLeftOf
                                             |    torightOf
                                             |    centerHorizontal
                                             |    centerVertical
                                             |    ================
                                             |
                                             |
                                             |    ================
                                             |    LinearLayout
                                             |    .LayoutParms
                                             |    ----------------
                                             |    gravity
                                             |    weight
                                             |    ================
                                             |
                                             |
                                             |    ================
                                             |    FrameLayout
                                             ---  .LayoutParms
                                                  ----------------
                                                  gravity
                                                  ================


画面のサイズは、要求サイズと実サイズの 2 種類ある。それぞれ、つぎのメソッドで取
得できる。

・サイズを取得する View クラスのメソッド
---
int getMeasuredWidth()  要求している幅
int getMeasuredHeight() 要求している高さ

int getWidth()          実際の幅
int getHeight()         実際の高さ
---


□ ViewGroup クラス

java.lang.Object
   +    android.view.View
        +    android.view.ViewGroup

ウィジェットを取りまとめることができるビューのスーパークラス。


XML 属性(属性名の前に、名前空間プレフィックス android: がつく)
---
android:addStatesFromChildren   
android:alwaysDrawnWithCache    
android:animateLayoutChanges    
android:animationCache            
android:clipChildren            
android:clipToPadding            
android:descendantFocusability  
android:layoutAnimation         
android:persistentDrawingCache  
---


□ ViewGroup.LayoutParams クラス

java.lang.Object
   +    android.view.ViewGroup.LayoutParams

ViewGroup の内部クラスで、画面のサイズに関するスーパークラス。


XML 属性(属性名の前に、名前空間プレフィックス android: がつく)
---
android:layout_height   ビューの高さ 
android:layout_width    ビューの幅
---

属性の値
---
属性値       値   説明
fill_parent  -1   他のウィジェットの処理後にあまっている部分もすべて使うサイズ
match_parent -1   fill_parent と同じ(Android2.2 以降ではこちらが推奨)
wrap_content -2   ウィジェットが入るサイズ。ウィジェットが大きいときは折り返す
値           正数 単位つきの実正数を指定
---


△ 実正数の単位

Dimension
http://developer.android.com/intl/ja/guide/topics/resources/more-resources.html#Dimension

---
dp  Density-independent Pixels - dpiを基本にした相対的な単位。
    160dpi の画面では、1dp = 1px となる
sp  Scale-independent Pixels - フォントサイズを基本にした相対的な単位。
pt  Points - 物理的な画面での大きさ (1/72 inch = 1 pt)
px  Pixels - 物理的な画面でのドット数
mm  Millimeters - 物理的な画面での大きさ
in  Inches - 物理的な画面での大きさ
---


□ ViewGroup.MarginLayoutParams

java.lang.Object
   +    android.view.ViewGroup.LayoutParams
        +    android.view.ViewGroup.MarginLayoutParams

ViewGroup.LayoutParams のサブクラスで、レイアウトのマージンに関するクラス。


XML 属性(属性名の前に、名前空間プレフィックス android: がつく)
---
android:layout_marginBottom
android:layout_marginLeft  
android:layout_marginRight 
android:layout_marginTop   
---

Java では、
    void  setMargins(int left, int top, int right, int bottom)
メソッドを使って動的に変更できる。

                                                                            以上


[Java] アナグラムを作る

2012年03月19日 | Java
[Java] アナグラムを作る
================================================================================

アナグラム (anagram) とは、言葉遊びのひとつ。単語または文の中の文字をいくつか入れ替えることによってまったく別の意味にさせる遊びである。
(ウィキペディア、http://ja.wikipedia.org/wiki/%E3%82%A2%E3%83%8A%E3%82%B0%E3%83%A9%E3%83%A0 より)

ただ、今回のプログラムは、意味はなく、文字を入れ替えるだけである。
ただし、つぎの点には気をつけた。
・同じ文字列にならない
・単語の先頭に行頭禁則和字が来ない

行頭禁則和字は以下の文字とする。
    ヽヾーァィゥェォッャュョヮヵヶぁぃぅぇぉっゃゅょゎ


実際に必要なメソッドは、つぎの 2 つ。

public static String anagram(String s)        文字列のアナグラムを作る。
private static boolean isIllegalCharacters(List<Character> list) 
                                              不正な文字列かどうか判断する。 

これとは別に、単なる配列検索のユーティリティとして、つぎのメソッドを用意した。

private static int search(char[] a, char key) 配列から値を検索する。


□ Anagram.java
---
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;

public class Anagram {

    public static void main(String[] args) {

        System.out.println(anagram(""));
        System.out.println(anagram("ア"));
        System.out.println(anagram("アイスクリーム"));
        System.out.println(anagram("ドック"));
        System.out.println(anagram("キャット"));
    }

    /**
     * 文字列のアナグラムを作る。
     * ただし、アナグラムを作れないような文字数のときは、その文字列をそのまま返す。
     * 
     * @param s
     *            文字列
     * @return s のアナグラム
     */
    public static String anagram(String s) {
        if (s.length() < 2) {
            return s;
        }
        
        List<Character> list = new ArrayList<Character>();
        for (char c : s.toCharArray()) {
            list.add(c);
        }

        char[] cs;
        
        do {    // 同じ文字列でないようにする
            do {    // 不正な文字列でないようにする
                Collections.shuffle(list);
            } while (isIllegalCharacters(list));
            
            cs = new char[list.size()];
            for (int i = 0; i < cs.length; i++) {
                cs[i] = list.get(i);
            }
            
        } while (String.valueOf(cs).equals(s));
        
        return String.valueOf(cs);
    }

    /**
     * 不正な文字列かどうか判断する。 
     * ここでは、行頭禁則文字があると、不正な文字列とする。
     * 行頭禁則和字は以下の文字
     *     ヽヾーァィゥェォッャュョヮヵヶぁぃぅぇぉっゃゅょゎ
     * @param list
     *            文字列を表すリスト
     * @return 不正な文字列であれば、true
     */
    private static boolean isIllegalCharacters(List<Character> list) {
        final char[] START_LINE_ILLEGAL_CHARACTERS = { 
            'ヽ', 'ヾ', 'ー', 
            'ァ', 'ィ', 'ゥ', 'ェ', 'ォ', 'ッ', 'ャ', 'ュ', 'ョ', 'ヮ', 'ヵ', 'ヶ', 
            'ぁ', 'ぃ', 'ぅ', 'ぇ', 'ぉ', 'っ', 'ゃ', 'ゅ', 'ょ', 'ゎ',
        };

        return search(START_LINE_ILLEGAL_CHARACTERS, list.get(0)) != -1;
    }

    /**
     * 指定された char 値の配列から指定された値を検索する。
     * @param a 検索される配列
     * @param key 検索される値
     * @return 配列に検索キーがある場合は検索キーのインデックス。 検索キーがリストにない場合は -1.
     */
    private static int search(char[] a, char key) {
        for (int i = 0; i < a.length; i++) {
            if (a[i] == key) {
                return i;
            }
        }

        return -1;
    }

}
---

□ 実行結果例
---
リアイクースム
ドクッ
キットャ
---
                                                                            以上


[Android] フォント

2012年03月17日 | Android
[Android] フォント
================================================================================

■ 組込みのフォント

つぎの 4 つのフォントが組込みで使える。
    normal
    sans
    serif
    monospace

これらは、android:typeface 属性で出てくるものである。
ただし、日本語のフォントは変わらないみたい。

また、フォントのスタイルには、つぎの 3 つがある。
    normal
    bold
    italic


■ フォントの追加

また、使いたいフォントを、Android 実機に追加して使用することもできる。

フォントは True Type Font(ttf ファイル)を assets フォルダーの中に入れる。
今回は、assets フォルダーの中に fonts フォルダーを作り、ダウンロードしてきた 3 
つの ttf ファイルを入れて、それをボタンによってサイクリックに換えている。

フォントは
しねきゃぷしょん
http://chiphead.jp/font.htm
よりダウンロードしたものを使っている。

    字幕フォント           cinecaption227.ttf    
    ファミコン・フォント   FAMania2.6.ttf    
    トンパ文字             tompa1.50.ttf    


設定としては、ttf ファイルを assets フォルダーに入れたら、プログラムでは、以下の
ようにするだけ。

    Typeface tf = Typeface.createFromAsset(getAssets(), ttfファイルへのパス);
    ウィジェット.setTypeface(tf);


これらの指定は、ウィジェット全体に適用する。

---
★ 文章の中の一部だけを変更したいような場合は、HTML などを使う必要があるかもしれ
ない。
---

---
★ 実機の機種によって、追加したフォントが使えたり使えなかったりする。字幕みたい
なフォント cinecaption227.ttf が、IdeaPad A1 では使えて、Dell Streak では使えな
い。ただし、例外が出るわけではなく、対応する文字がないという感じ。なぜ?
なお、エミュレーターでも出なかった。
---


▲ アクティビティ

ダウンロードしてきたフォントを、ボタンがクリックされるたびにサイクリックに変更す
る。

□ TrueTypeFont01Activity.java
---
package jp.marunomaruno.android.truetypefont;

import android.app.Activity;
import android.graphics.Typeface;
import android.os.Bundle;
import android.view.View;
import android.widget.TextView;

public class TrueTypeFont01Activity extends Activity {
    private int fontIndex = 0; // (1)
    private String[] names;
    private String[] descriptions;
    private Typeface[] typefaces;

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

        names = getResources().getStringArray(R.array.fontName); // (2)
        descriptions = getResources().getStringArray(R.array.fontDescription); // (3)

        String[] files = getResources().getStringArray(R.array.fontFile); // (4)
        typefaces = new Typeface[files.length];
        for (int i = 1; i < typefaces.length; i++) {
            typefaces[i] = Typeface.createFromAsset(getAssets(), "fonts/"
                    + files[i]); // (5)
        }
        typefaces[0] = Typeface.DEFAULT; // (6)
    }

    public void onClickNextFont(View view) throws Exception {
        try {
            fontIndex++; // (7)
            fontIndex %= names.length; // (8)

            TextView fontName = (TextView) findViewById(R.id.fontName);
            fontName.setText(names[fontIndex]);

            TextView fontText = (TextView) findViewById(R.id.fotTtext);
            fontText.setTypeface(typefaces[fontIndex]); // (9)
            fontText.setText(String.format("%s%n%s%n",
                    getString(R.string.hello), descriptions[fontIndex]));

        } catch (Exception e) { // (10)
            e.printStackTrace();
            throw e;
        }
    }
}
---

(1)(7)(8) サイクリックに変更するためのインデックス

インデックスの定義

    private int fontIndex = 0; // (1)

フォントが使われるたびにインクリメントして、フォントの数で割った余りをふたたび使
うようにする。

    fontIndex++; // (7)
    fontIndex %= names.length; // (8)


(2)(3)(4) フォント名、ファイル名、フォントを使った文章を取得

res/values/strings.xml に、string-array 要素として設定してある。

    names = getResources().getStringArray(R.array.fontName); // (2)
    descriptions = getResources().getStringArray(R.array.fontDescription); // (3)
    String[] files = getResources().getStringArray(R.array.fontFile); // (4)


(5) Typeface オブジェクトの生成

    typefaces[i] = Typeface.createFromAsset(getAssets(), "fonts/"
                + files[i]); // (5)


(6) デフォルト・フォントを設定

    typefaces[0] = Typeface.DEFAULT; // (6)


(9) Typeface オブジェクトの設定

    fontText.setTypeface(typefaces[fontIndex]); // (9)


(10) 例外の処理

フォントのファイル (ttf ファイル)がないときは、RuntimeException がスローされる。
メッセージはつぎのとおり。
    java.lang.RuntimeException: native typeface cannot be made

キャッチして、スタックトレースだけ出し、今回は、そのままスローしなおす。

    catch (Exception e) { // (10)



□ Typeface クラス

java.lang.Object
   +    android.graphics.Typeface

フォントを管理するクラス。

定数としては、フォントのタイプを表すものと、組込みのフォントが用意されている。

定数
---
int       BOLD    
int       BOLD_ITALIC    
int       ITALIC    
int       NORMAL    
Typeface  DEFAULT        
Typeface  DEFAULT_BOLD
Typeface  MONOSPACE    
Typeface  SANS_SERIF    
Typeface  SERIF        
---


ttf ファイルを指定して、フォントを生成する。

メソッド
---
static Typeface  create(String familyName, int style)
static Typeface  create(Typeface family, int style)
static Typeface  createFromAsset(AssetManager mgr, String path)
static Typeface  createFromFile(String path)
static Typeface  createFromFile(File path)
static Typeface  defaultFromStyle(int style)
int              getStyle()
final boolean    isBold()
final boolean    isItalic()
---


▲ レイアウト

□ res/layout/main.xml
---
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="vertical" >

    <TextView
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:text="normal アイスクリーム"
        android:textAppearance="?android:attr/textAppearanceLarge"
        android:typeface="normal" />    <!-- (1) -->

    <TextView
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:text="sans アイスクリーム"
        android:textAppearance="?android:attr/textAppearanceLarge"
        android:typeface="sans" />    <!-- (2) -->

    <TextView
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:text="serif アイスクリーム"
        android:textAppearance="?android:attr/textAppearanceLarge"
        android:typeface="serif" />    <!-- (3) -->

    <TextView
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:text="monospace アイスクリーム"
        android:textAppearance="?android:attr/textAppearanceLarge"
        android:typeface="monospace" />    <!-- (4) -->

    <TextView
        android:id="@+id/fontName"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:text="@string/defaultFont"
        android:textAppearance="?android:attr/textAppearanceLarge" /> <!-- (5) -->

    <Button
        android:id="@+id/nextFontButton"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:onClick="onClickNextFont"
        android:text="@string/nextFontButton"
        android:textAppearance="?android:attr/textAppearanceLarge" />

    <TextView
        android:id="@+id/fotTtext"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:text="@string/hello"
        android:textAppearance="?android:attr/textAppearanceLarge" /> <!-- (6) -->

</LinearLayout>
---


(1)(2)(3)(4) 組込みフォントを表示

android:typeface 属性を使って、それぞれ、組込みフォントを表示している。
    normal
    sans
    serif
    monospace


(5) android:typeface 属性なし

デフォルトは normal かな。


(6) 追加フォントの文字を表示


上記サンプルでは使っていないが、太字などにする android:textStyle 属性もある。
以下の値が指定できる。
    normal
    bold
    italic

複数の値を指定したいときは、パイプ(|) を使って指定する。


▲ リソース

□ res/values/strings.xml
---
<?xml version="1.0" encoding="utf-8"?>
<resources>

    <string name="hello">Hello World, TrueTypeFont01Activity!</string>
    <string name="app_name">TrueTypeFont01</string>
    <string name="defaultFont">デフォルトのフォント</string>
    <string name="nextFontButton">次のフォント</string>

    <string-array name="fontName">
        <item>@string/defaultFont</item>
        <item>字幕フォント</item>
        <item>ファミコン・フォント</item>
        <item>トンパ文字</item>
    </string-array>
    <string-array name="fontFile">
        <item>-</item>
        <item>cinecaption227.ttf</item>
        <item>FAMania2.6.ttf</item>
        <item>tompa1.50.ttf</item>
    </string-array>
    <string-array name="fontDescription">
        <item>@string/defaultFont</item>
        <item>字幕みたいなフォント</item>
        <item>ファミコンもどきのフォント</item>
        <item>阿葵悪安伊亥一壱丑浦英猿岡億下加夏賀介角</item> 
                    <!-- トンパ文字に対応する文字が少ないため、適当な文字列 -->
    </string-array>

</resources>
--

なお、トンパ文字に対応する文字が少ないため、適当な文字列を記述している。
フォントの説明によると、現在は 150 文字を登録している、とのこと。

                                                                            以上


[Android] フォント

2012年03月17日 | Android

[Android] フォント
================================================================================

■ 組込みのフォント

つぎの 4 つのフォントが組込みで使える。
normal
sans
serif
monospace

これらは、android:typeface 属性で出てくるものである。
ただし、日本語のフォントは変わらないみたい。

また、フォントのスタイルには、つぎの 3 つがある。
normal
bold
italic


■ フォントの追加

また、使いたいフォントを、Android 実機に追加して使用することもできる。

フォントは True Type Font(ttf ファイル)を assets フォルダーの中に入れる。
今回は、assets フォルダーの中に fonts フォルダーを作り、ダウンロードしてきた 3
つの ttf ファイルを入れて、それをボタンによってサイクリックに換えている。

フォントは
しねきゃぷしょん
http://chiphead.jp/font.htm
よりダウンロードしたものを使っている。

字幕フォント cinecaption227.ttf
ファミコン・フォント FAMania2.6.ttf
トンパ文字 tompa1.50.ttf


設定としては、ttf ファイルを assets フォルダーに入れたら、プログラムでは、以下の
ようにするだけ。

Typeface tf = Typeface.createFromAsset(getAssets(), ttfファイルへのパス);
ウィジェット.setTypeface(tf);


これらの指定は、ウィジェット全体に適用する。

---
★ 文章の中の一部だけを変更したいような場合は、HTML などを使う必要があるかもしれ
ない。
---

---
★ 実機の機種によって、追加したフォントが使えたり使えなかったりする。字幕みたい
なフォント cinecaption227.ttf が、IdeaPad A1 では使えて、Dell Streak では使えな
い。ただし、例外が出るわけではなく、対応する文字がないという感じ。なぜ?
なお、エミュレーターでも出なかった。
---


▲ アクティビティ

ダウンロードしてきたフォントを、ボタンがクリックされるたびにサイクリックに変更す
る。

□ TrueTypeFont01Activity.java
---
package jp.marunomaruno.android.truetypefont;

import android.app.Activity;
import android.graphics.Typeface;
import android.os.Bundle;
import android.view.View;
import android.widget.TextView;

public class TrueTypeFont01Activity extends Activity {
private int fontIndex = 0; // (1)
private String[] names;
private String[] descriptions;
private Typeface[] typefaces;

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

names = getResources().getStringArray(R.array.fontName); // (2)
descriptions = getResources().getStringArray(R.array.fontDescription); // (3)

String[] files = getResources().getStringArray(R.array.fontFile); // (4)
typefaces = new Typeface[files.length];
for (int i = 1; i < typefaces.length; i++) {
typefaces[i] = Typeface.createFromAsset(getAssets(), "fonts/"
+ files[i]); // (5)
}
typefaces[0] = Typeface.DEFAULT; // (6)
}

public void onClickNextFont(View view) throws Exception {
try {
fontIndex++; // (7)
fontIndex %= names.length; // (8)

TextView fontName = (TextView) findViewById(R.id.fontName);
fontName.setText(names[fontIndex]);

TextView fontText = (TextView) findViewById(R.id.fotTtext);
fontText.setTypeface(typefaces[fontIndex]); // (9)
fontText.setText(String.format("%s%n%s%n",
getString(R.string.hello), descriptions[fontIndex]));

} catch (Exception e) { // (10)
e.printStackTrace();
throw e;
}
}
}
---

(1)(7)(8) サイクリックに変更するためのインデックス

インデックスの定義

private int fontIndex = 0; // (1)

フォントが使われるたびにインクリメントして、フォントの数で割った余りをふたたび使
うようにする。

fontIndex++; // (7)
fontIndex %= names.length; // (8)


(2)(3)(4) フォント名、ファイル名、フォントを使った文章を取得

res/values/strings.xml に、string-array 要素として設定してある。

names = getResources().getStringArray(R.array.fontName); // (2)
descriptions = getResources().getStringArray(R.array.fontDescription); // (3)
String[] files = getResources().getStringArray(R.array.fontFile); // (4)


(5) Typeface オブジェクトの生成

typefaces[i] = Typeface.createFromAsset(getAssets(), "fonts/"
+ files[i]); // (5)


(6) デフォルト・フォントを設定

typefaces[0] = Typeface.DEFAULT; // (6)


(9) Typeface オブジェクトの設定

fontText.setTypeface(typefaces[fontIndex]); // (9)


(10) 例外の処理

フォントのファイル (ttf ファイル)がないときは、RuntimeException がスローされる。
メッセージはつぎのとおり。
java.lang.RuntimeException: native typeface cannot be made

キャッチして、スタックトレースだけ出し、今回は、そのままスローしなおす。

catch (Exception e) { // (10)



□ Typeface クラス

java.lang.Object
+ android.graphics.Typeface

フォントを管理するクラス。

定数としては、フォントのタイプを表すものと、組込みのフォントが用意されている。

定数
---
int BOLD
int BOLD_ITALIC
int ITALIC
int NORMAL
Typeface DEFAULT
Typeface DEFAULT_BOLD
Typeface MONOSPACE
Typeface SANS_SERIF
Typeface SERIF
---


ttf ファイルを指定して、フォントを生成する。

メソッド
---
static Typeface create(String familyName, int style)
static Typeface create(Typeface family, int style)
static Typeface createFromAsset(AssetManager mgr, String path)
static Typeface createFromFile(String path)
static Typeface createFromFile(File path)
static Typeface defaultFromStyle(int style)
int getStyle()
final boolean isBold()
final boolean isItalic()
---


▲ レイアウト

□ res/layout/main.xml
---
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical" >

<TextView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="normal アイスクリーム"
android:textAppearance="?android:attr/textAppearanceLarge"
android:typeface="normal" /> <!-- (1) -->

<TextView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="sans アイスクリーム"
android:textAppearance="?android:attr/textAppearanceLarge"
android:typeface="sans" /> <!-- (2) -->

<TextView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="serif アイスクリーム"
android:textAppearance="?android:attr/textAppearanceLarge"
android:typeface="serif" /> <!-- (3) -->

<TextView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="monospace アイスクリーム"
android:textAppearance="?android:attr/textAppearanceLarge"
android:typeface="monospace" /> <!-- (4) -->

<TextView
android:id="@+id/fontName"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="@string/defaultFont"
android:textAppearance="?android:attr/textAppearanceLarge" /> <!-- (5) -->

<Button
android:id="@+id/nextFontButton"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:onClick="onClickNextFont"
android:text="@string/nextFontButton"
android:textAppearance="?android:attr/textAppearanceLarge" />

<TextView
android:id="@+id/fotTtext"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="@string/hello"
android:textAppearance="?android:attr/textAppearanceLarge" /> <!-- (6) -->

</LinearLayout>
---


(1)(2)(3)(4) 組込みフォントを表示

android:typeface 属性を使って、それぞれ、組込みフォントを表示している。
normal
sans
serif
monospace


(5) android:typeface 属性なし

デフォルトは normal かな。


(6) 追加フォントの文字を表示


上記サンプルでは使っていないが、太字などにする android:textStyle 属性もある。
以下の値が指定できる。
normal
bold
italic

複数の値を指定したいときは、パイプ(|) を使って指定する。


▲ リソース

□ res/values/strings.xml
---
<?xml version="1.0" encoding="utf-8"?>
<resources>

<string name="hello">Hello World, TrueTypeFont01Activity!</string>
<string name="app_name">TrueTypeFont01</string>
<string name="defaultFont">デフォルトのフォント</string>
<string name="nextFontButton">次のフォント</string>

<string-array name="fontName">
<item>@string/defaultFont</item>
<item>字幕フォント</item>
<item>ファミコン・フォント</item>
<item>トンパ文字</item>
</string-array>
<string-array name="fontFile">
<item>-</item>
<item>cinecaption227.ttf</item>
<item>FAMania2.6.ttf</item>
<item>tompa1.50.ttf</item>
</string-array>
<string-array name="fontDescription">
<item>@string/defaultFont</item>
<item>字幕みたいなフォント</item>
<item>ファミコンもどきのフォント</item>
<item>阿葵悪安伊亥一壱丑浦英猿岡億下加夏賀介角</item>
<!-- トンパ文字に対応する文字が少ないため、適当な文字列 -->
</string-array>

</resources>
--

なお、トンパ文字に対応する文字が少ないため、適当な文字列を記述している。
フォントの説明によると、現在は 150 文字を登録している、とのこと。

以上

[Android] インテント (2) - アクティビティからの結果の受け取り

2012年03月09日 | Android
[Android] インテント (2) - アクティビティからの結果の受け取り
================================================================================

インテントを使って呼び出したアクティビティから、結果を受け取ることができる。

呼び出す側:

・startActivityForResult() メソッドを使ってアクティビティを起動する

・onActivityResult() メソッドをオーバーライドして、結果を受け取ったときの処理を記述する

呼び出された側:

・必要に応じて、結果を戻すためのインテント・オブジェクトを生成して、データを設定する

・setResult() メソッドで、結果コードや戻すデータを設定する

・finish() メソッドで、アクティビティを終了する


■ 呼び出す側

▲ アクティビティ

インテント起動ボタンを押下したら、startActivityForResult() メソッドを使ってアクティビティを起動する。

onActivityResult() メソッドをオーバーライドして、結果を受け取ったときの処理を記述する。このとき、単語が指定されていれば、この単語を逆順にした文字列を表示する。
単語が指定されていなければ、その旨のメッセージを表示する。


□ Intent02Activity.java
---
package jp.marunomaruno.android.intent;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;

public class Intent02Activity extends Activity {
    private static final int REQUEST_REVERSE_ACTIVITY = 1;    // (1)

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

    /**
     * 暗黙的にインテントを起動する。
     * 
     * @param view
     */
    public void onClickImplisitButton(View view) {
        EditText edit1 = (EditText) findViewById(R.id.editText1);

        Intent intent = new Intent(Intent.ACTION_SEND);
        intent.putExtra("message", edit1.getText());
        startActivityForResult(intent, REQUEST_REVERSE_ACTIVITY);    // (2)
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode,
            Intent data) {    // (3)
        super.onActivityResult(requestCode, resultCode, data);    // (4)

        TextView text1 = (TextView) findViewById(R.id.text1);

        switch (requestCode) {    // (5)
        case REQUEST_REVERSE_ACTIVITY:     // (6)
            switch (resultCode) {    // (7)
            case Activity.RESULT_OK:     // (8)
                String reverse = data.getStringExtra("reverse");
                text1.setText(reverse);
                break;
                
            case RESULT_FIRST_USER + OtherActivity.NO_WORDS:     // (9)
                text1.setText(R.string.noWordsMessage);
                break;
                
            default:
                text1.setText(String.format("onActivityResult() resultCode=%d", 
											resultCode));
                break;
            }
            break;
            
        default:
            text1.setText(String.format("onActivityResult() requestCode=%d", 
											requestCode));
            break;
        }
    }
}
---

(1) 逆順文字列作成のためのインテント要求コードを定義する

    private static final int REQUEST_REVERSE_ACTIVITY = 1;    // (1)

これは、startActivityForResult() メソッドで指定する。これによって、アクティビティから結果が戻ってきたら、この値を確認することで、どのインテントを使ってアクティビティを呼び出したかがわかる。


(2) 結果を受け取るためのインテントを起動する

要求コードを指定する。

    startActivityForResult(intent, REQUEST_REVERSE_ACTIVITY);    // (2)


(3)(4) インテントの結果を受け取る

Activity クラスのこのメソッドをオーバーライドする。

    protected void onActivityResult(int requestCode, int resultCode,
            Intent data) {    // (3)

requestCode: startActivityForResult() で指定した要求コード
resultCode:  戻りコード
data:        データ

スーパークラスの同メソッドを呼び出す。

    super.onActivityResult(requestCode, resultCode, data);    // (4)


(5) 要求コードによって処理を切り分ける

    switch (requestCode) {    // (5)


(6) 逆順文字列作成の要求コード

    case REQUEST_REVERSE_ACTIVITY:     // (6)


(7) 結果の戻りコードによって処理を切り分ける

    switch (resultCode) {    // (7)

Activity クラスで定義している結果コードは次の 3 つ。
---
int  RESULT_CANCELED     0  キャンセルされた
int  RESULT_FIRST_USER   1  自分で定義する結果コードの最初の値
int  RESULT_OK          -1  結果成功
---

したがって、自分で定義する結果コードは 1 から順番に振る方がよい。


(8) 結果が OK のときの処理

    case RESULT_OK:     // (8)


(9) 単語が指定していなかったときの処理

    case RESULT_FIRST_USER + OtherActivity.NO_WORDS:     // (9)

値としては、RESULT_FIRST_USER は 1 で、OtherActivity.NO_WORDS は 1 にしているので、2 となっている。
(RESULT_FIRST_USER は加えなくても大丈夫)


▲ レイアウト

□ res/layout/main.xml

※前回のプロジェクトと同じ


■ 呼び出される側

▲ アクティビティ

受け取った文字列の逆順文字列を送る。
受け取った文字列が空でなければ、逆順文字列を作る。そのときの結果コードは RESULT_OK (値は -1)。
文字列が空だったら、結果コードとして、2 (= RESULT_FIRST_USER + NO_WORDS) を設定して返す。

□ OtherActivity.java
---
package jp.marunomaruno.android.intent;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.TextView;

public class OtherActivity extends Activity {
    public static final int NO_WORDS = 1;    // (1)
    
    private String message;

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

        Intent intent = getIntent();
        TextView text1 = (TextView) findViewById(R.id.otherTextView1);
        message = intent.getCharSequenceExtra("message").toString();
        text1.setText(message);
    }

    public void onClickBackButton(View view) {
        Intent returnIntent = new Intent();    // (2)
        returnIntent.putExtra("reverse", reverse(message));    // (3)
        if (message.length() > 0) {
            setResult(RESULT_OK, returnIntent);    // (4)
            
        } else {
            setResult(RESULT_FIRST_USER + NO_WORDS, returnIntent);    // (5)

        }
        finish();    // (6)
    }

    /**
     * 文字列を逆並び順にした文字列を返す。
     * @param s 文字列
     * @return 逆並び順にした文字列
     */
    private String reverse(String s) {
        return new StringBuilder(s).reverse().toString();
    }
}
---

(1) 文字列が空のときの結果コード

    public static final int NO_WORDS = 0;    // (1)


(2)(3) 戻すためのデータを設定する

そのためのインテント・オブジェクトを生成する。

    Intent returnIntent = new Intent();    // (2)

インテントにデータを設定する。このとき、逆並び順の文字列を作る。

    returnIntent.putExtra("reverse", reverse(message));    // (3)


(4) 空の文字列でなければ、結果コード RESULT_OK とする

    setResult(RESULT_OK, returnIntent);    // (4)


(5) 空の文字列のとき、その旨の結果コードを指定する

    setResult(RESULT_FIRST_USER + NO_WORDS, returnIntent);    // (5)


(6) アクティビティを終わる

    finish();    // (6)


▲ レイアウト

呼び出し元のアクティビティに戻るボタンをつけた。

□ res/layout/other.xml
---
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="vertical" >

    <TextView
        android:id="@+id/otherTextView1"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:text=""
        android:textAppearance="?android:attr/textAppearanceLarge" />

    <Button
        android:id="@+id/backButton"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:onClick="onClickBackButton"
        android:text="@string/backButtonLabel" />

</LinearLayout>
---


■ マニュフェスト

※前回のプロジェクトと同じ


■ リソース

□ res/values/strings.xml
---
<?xml version="1.0" encoding="utf-8"?>
<resources>
    <string name="app_name">Intent02</string>
    <string name="implicitButtonLabel">逆並び順文字列を作る</string>
    <string name="backButtonLabel">確認</string>
    <string name="noWordsMessage">単語が指定されていません。</string>
</resources>
---

                                                                            以上



[Android] インテント (1) - インテントを使ったアクティビティの呼び出し

2012年03月08日 | Android
[Android] インテント (1) - インテントを使ったアクティビティの呼び出し
================================================================================

インテントは、プログラムの実行に関する情報を管理するメッセージである。
プログラムの実行時に、実行に関する情報がインテントというメッセージにまとめられる。
このインテントを発行することで、プログラムを実行させることができる。また、逆に、
プログラムには、自身が受け取れるインテントの種類を記述できる。

インテントは、つぎの主要な情報によって構成している。
・アクション        動作
・カテゴリー        インテントに対する追加のメタデータ
・データ            インテントに与えるデータで、URI として表現
・エクストラ        Bundle 型のインテントに渡されるデータ
・フラグ            アクティビティの起動方法
・タイプ            MIME タイプ(操作したいリソースの種類)
・コンポーネント    インテントを利用するパッケージやクラスを明示的に指定

アクションとカテゴリーは単なる文字列で表現している。
データは Uri オブジェクトで定義する。Uri オブジェクトは、RFC3986 で定義された 
URI である。


インテントには、メッセージの送信先の指定方法によって、次の 2 つの種類がある。

・明示的インテント

メッセージを送る相手のプログラムのクラス名を直接指定する

・暗示的(暗黙的)インテント

相手のプログラムにさせたいこと(アクション)、そのときに必要なデータを指定すること
で、システムが自動的にプログラムを指定する。暗黙的インテントで、アクティビティが
インテントを受け取るためには、つぎの暗黙的なルーティング 3 つの条件をすべて満た
している必要がある。

コンストラクターとしては、以下のようなものがある。
 Intent(String action) 
 Intent(String action, Uri uri) 

また、メソッドで設定するには、以下のものがある。

Intent  setAction(String action) 

Intent  setData(Uri data) 
Intent  setDataAndType(Uri data, String type) 

Intent  setType(String type) 
Intent  putExtra(String name, 型 value) 
Intent  putExtra(String name, 型[] value) 


暗黙的なルーティング
・アクティビティは指定されたアクションをサポートする
・MIME タイプが指定されている場合、アクティビティはそれをサポートする
・アクティビティはインテントで指定されたカテゴリーをすべてサポートする


インテントの起動は、Activity クラスの
    startActivity(インテント)
を使う。また、結果を受け取りたい場合は、
    startActivityForResult(インテント, リクエスト・コード)
を使う。また、結果は、
    onActivityResult(int requestCode, int resultCode, Intent data)
をオーバーライドする。
呼び出された側のアクティビティでは、戻りコードは、
    setResult(戻りコード, インテント);
を使って設定する。


アクションとデータの例
------------------- --------------------------- --------------------------------
アクション          データ                      動作
------------------- --------------------------- --------------------------------
ACTION_VIEW         http://アドレス             ブラウザーで指定するURL
                    content://contacts/people/  内臓の電話帳を表示
                    geo:軽度,緯度               地図を表示
                    geo:0,0?q=住所              地図を表示
ACTION_CALL         tel://電話番号              電話をかける
ACTION_DIAL         tel://電話番号              ダイヤル画面を表示
ACTION_EDIT         URI                         URIで示されるアドレス長を編集
ACTION_WEB_SEARCH   検索文字列                  ブラウザーを開き、Googleで検索
------------------- --------------------------- --------------------------------

Intents and Intent Filters
http://developer.android.com/intl/ja/guide/topics/intents/intents-filters.html

ソフトウェア技術ドキュメントを勝手に翻訳 
Android 開発ガイド > フレームワークトピック > 4. インテントとインテントフィルタ
https://sites.google.com/a/techdoctranslator.com/jp/android/guide/intents-filters


■ 呼び出す側

同じアプリケーション内で、画面を切り替えるサンプル。
画面はアクティビティ・オブジェクトなので、ある画面から別の画面に切り替えるのに、
このインテントを使って行う。


▲ アクティビティ

テキスト・フィールドから取得した文字列を、つぎの画面に渡す。
このとき、つぎの画面の起動方法として、明示的にインテントを指定する方法と、暗黙的
にインテントを指定する 2 つの方法を使っている。

□ Intent01Activity.java
---
package jp.marunomaruno.android.intent;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.EditText;

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

    /**
     * 明示的にインテントを起動する。
     * 
     * @param view
     */
    public void onClickExplisitButton(View view) {
        EditText edit1 = (EditText) findViewById(R.id.editText1);

        Intent intent = new Intent(this, OtherActivity.class);    // (1)
        intent.putExtra("message", edit1.getText());    // (2)
        startActivity(intent);    // (3)
    }

    /**
     * 暗黙的にインテントを起動する。
     * 
     * @param view
     */
    public void onClickImplisitButton(View view) {
        EditText edit1 = (EditText) findViewById(R.id.editText1);

        Intent intent = new Intent(Intent.ACTION_SEND);    // (4)
        intent.putExtra("message", edit1.getText());
        startActivity(intent);
    }
}
---

(1) 明示的にインテント・オブジェクトを生成する

コンテキストとクラスを明示的に指定してインテント・オブジェクトを生成する。

    Intent intent = new Intent(this, OtherActivity.class);    // (1)


明示的にインテント・オブジェクトを生成するコンストラクター
---
Intent(Context packageContext, Class<?> cls) 
---

または、空のインテント・オブジェクトを作って、つぎのメソッドでクラスを設定する。
---
Intent  setClass(Context packageContext, Class<?> cls) 
Intent  setClassName(Context packageContext, String className) 
Intent  setClassName(String packageName, String className) 
---

自分のアプリケーションでないものなどは、3 番目のメソッドを利用して指定することも
できる。たとえば、ブラウザーなどはつぎのように指定することができる。
    setClassName("com.android.browser", "com.android.browser.BrowserActivity")


(2) 渡すデータを設定する

Uri オブジェクト以外のデータは、つぎのように、putExtra() メソッドを利用して、つ
ぎのアクティビティに渡すことができる。

putExtra() の第 1 引数には、渡すデータを意味する文字列。

    intent.putExtra("message", edit1.getText());    // (2)

データの取得側では、この "message" をキーとして、データを取得する。
なお、汎用のキーとして、Intent クラスの定数に、EXTRA_xxx という形でキーが用意さ
れているので、それを使うこともできる。


・Extra データ設定関係のメソッド(スカラーのもののみ)
---
Intent     putExtra(String name, boolean value)
Intent     putExtra(String name, byte value)
Intent     putExtra(String name, double value)
Intent     putExtra(String name, char value)
Intent     putExtra(String name, int value)
Intent     putExtra(String name, float value)
Intent     putExtra(String name, long value)
Intent     putExtra(String name, short value)
Intent     putExtra(String name, CharSequence value)
Intent     putExtra(String name, String value)
Intent     putExtra(String name, Serializable value)
---


(3) アクティビティを起動する

startActivity() メソッドにより、つぎのアクティビティを起動する。

    startActivity(intent);    // (3)

なお、指定されたアクティビティがない場合、
android.content.ActivityNotFoundException
がスローされる。


(4) 暗黙的にインテント・オブジェクトを生成する

何をするべきものなのかというアクションを指定して、インテント・オブジェクトを生成
する。

    Intent intent = new Intent(Intent.ACTION_SEND);    // (4)


暗黙的にインテント・オブジェクトを生成するコンストラクター
---
Intent(String action) 
Intent(String action, Uri uri) 
---


▲ レイアウト

明示的と暗黙的にインテントを起動するボタン。

□ res/layout/main.xml
---
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="vertical" >

    <TextView
        android:id="@+id/text1"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:text=""
        android:textAppearance="?android:attr/textAppearanceLarge" />

    <EditText
        android:id="@+id/editText1"
        android:layout_width="match_parent"
        android:layout_height="wrap_content" >

        <requestFocus />
    </EditText>

    <Button
        android:id="@+id/explisitButton"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:onClick="onClickExplisitButton"
        android:text="@string/explicitButtonLabel" />

    <Button
        android:id="@+id/implisitButton"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:onClick="onClickImplisitButton"
        android:text="@string/implicitButtonLabel" />
</LinearLayout>
---


■ 呼び出される側

▲ 呼び出されるアクティビティのクラス

これは、単に渡されたデータをテキスト・ビューに設定して表示するだけのプログラム。

□ OtherActivity.java
---
package jp.marunomaruno.android.intent;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.widget.TextView;

public class OtherActivity extends Activity {

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

        Intent intent = getIntent();        // (1)
        TextView text1 = (TextView) findViewById(R.id.otherTextView1);
        text1.setText(intent.getCharSequenceExtra("message").toString()); // (2)
    }
}
---

(1) インテントを取得する

    Intent intent = getIntent();        // (1)


(2) データを取得する

putExtra(String, CharSequence) で設定したデータは、getCharSequenceExtra(String) 
で取得する。

    text1.setText(intent.getCharSequenceExtra("message").toString());    // (2)


・Extra データ設定関係のメソッド(スカラーのもののみ)
---
boolean       getBooleanExtra(String name, boolean defaultValue)
byte          getByteExtra(String name, byte defaultValue)
char          getCharExtra(String name, char defaultValue)
double        getDoubleExtra(String name, double defaultValue)
float         getFloatExtra(String name, float defaultValue)
int           getIntExtra(String name, int defaultValue)
long          getLongExtra(String name, long defaultValue)
short         getShortExtra(String name, short defaultValue)
CharSequence  getCharSequenceExtra(String name)
String        getStringExtra(String name)
Serializable  getSerializableExtra(String name)
---


▲ レイアウト

main のアクティビティから受け取った文字列を表示するだけのレイアウト。

□ res/layout/other.xml
---
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="vertical" >

    <TextView
        android:id="@+id/otherTextView1"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:text=""
        android:textAppearance="?android:attr/textAppearanceLarge" />

</LinearLayout>
---


■ Intent クラス

java.lang.Object 
   +  android.content.Intent 

プログラムの実行に関する情報を管理するメッセージのクラス。

・アクティビティ関係の標準アクション
---
ACTION_MAIN           メインプログラムの起動
ACTION_VIEW           ユーザーデータの表示
ACTION_ATTACH_DATA    添付データがついた
ACTION_EDIT           データの編集
ACTION_PICK           データからの取り出し
ACTION_CHOOSER        チューザーの表示
ACTION_GET_CONTENT    コンテントの取得
ACTION_DIAL           データをもとにダイアルする
ACTION_CALL           電話をかける
ACTION_SEND           データの送信
ACTION_SENDTO         メッセージの送信
ACTION_ANSWER         電話がかかってきた
ACTION_INSERT         指定のコンテナにデータを追加
ACTION_DELETE         データの削除
ACTION_RUN            データの実行
ACTION_SYNC           同期の開始
ACTION_PICK_ACTIVITY  アクティビティの選択
ACTION_SEARCH         検索
ACTION_WEB_SEARCH     Web 検索
ACTION_FACTORY_TEST   ファクトリーテスト用
---

・ブロードキャストの標準アクション
---
ACTION_TIME_TICK             現在の時刻が変更された
ACTION_TIME_CHANGED          時間が変更された
ACTION_TIMEZONE_CHANGED      タイムゾーンが変更された
ACTION_BOOT_COMPLETED        起動の完了
ACTION_PACKAGE_ADDED         パッケージの追加
ACTION_PACKAGE_CHANGED       パッケージの変更
ACTION_PACKAGE_REMOVED       パッケージの削除
ACTION_PACKAGE_RESTARTED     パッケージのリストア
ACTION_PACKAGE_DATA_CLEARED  パッケージ・データの初期化
ACTION_UID_REMOVED           ユーザーID の削除
ACTION_BATTERY_CHANGED       バッテリー状況の変更
ACTION_POWER_CONNECTED       電源接続
ACTION_POWER_DISCONNECTED    バッテリー起動への切替
ACTION_SHUTDOWN              シャットダウン
---

・主なカテゴリー
---
CATEGORY_DEFAULT     標準カテゴリ
CATEGORY_BROWSABLE   ブラウザから安全に起動することが可能
CATEGORY_TAB         TabActivity 内のタブ
CATEGORY_LAUNCHER    ホーム画面のアイコンから起動可能
CATEGORY_INFO        パッケージ情報が提供されている
CATEGORY_HOME        ホームスクリーンを表示する
CATEGORY_PREFERENCE  プリファレンスパネルがターゲット
CATEGORY_TEST        テストとして使用
---

・拡張データ
---
EXTRA_ALARM_COUNT 
EXTRA_BCC 
EXTRA_CC 
EXTRA_CHANGED_COMPONENT_NAME 
EXTRA_DATA_REMOVED 
EXTRA_DOCK_STATE 
EXTRA_DOCK_STATE_HE_DESK 
EXTRA_DOCK_STATE_LE_DESK 
EXTRA_DOCK_STATE_CAR 
EXTRA_DOCK_STATE_DESK 
EXTRA_DOCK_STATE_UNDOCKED 
EXTRA_DONT_KILL_APP 
EXTRA_EMAIL 
EXTRA_INITIAL_INTENTS 
EXTRA_INTENT 
EXTRA_KEY_EVENT 
EXTRA_PHONE_NUMBER 
EXTRA_REMOTE_INTENT_TOKEN 
EXTRA_REPLACING 
EXTRA_SHORTCUT_ICON 
EXTRA_SHORTCUT_ICON_RESOURCE 
EXTRA_SHORTCUT_INTENT 
EXTRA_STREAM 
EXTRA_SHORTCUT_NAME 
EXTRA_SUBJECT 
EXTRA_TEMPLATE 
EXTRA_TEXT 
EXTRA_TITLE 
EXTRA_UID 
---

・フラグ
---
FLAG_ACTIVITY_BROUGHT_TO_FRONT
FLAG_ACTIVITY_CLEAR_TASK 
FLAG_ACTIVITY_CLEAR_TOP 
FLAG_ACTIVITY_CLEAR_WHEN_TASK_RESET 
FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS 
FLAG_ACTIVITY_FORWARD_RESULT 
FLAG_ACTIVITY_LAUNCHED_FROM_HISTORY 
FLAG_ACTIVITY_MULTIPLE_TASK 
FLAG_ACTIVITY_NEW_TASK 
FLAG_ACTIVITY_NO_ANIMATION 
FLAG_ACTIVITY_NO_HISTORY 
FLAG_ACTIVITY_NO_USER_ACTION 
FLAG_ACTIVITY_PREVIOUS_IS_TOP  
FLAG_ACTIVITY_REORDER_TO_FRONT 
FLAG_ACTIVITY_RESET_TASK_IF_NEEDED 
FLAG_ACTIVITY_SINGLE_TOP 
FLAG_ACTIVITY_TASK_ON_HOME 
FLAG_DEBUG_LOG_RESOLUTION 
FLAG_EXCLUDE_STOPPED_PACKAGES 
FLAG_FROM_BACKGROUND 
FLAG_GRANT_READ_URI_PERMISSION 
FLAG_GRANT_WRITE_URI_PERMISSION 
FLAG_INCLUDE_STOPPED_PACKAGES 
FLAG_RECEIVER_REGISTERED_ONLY 
FLAG_RECEIVER_REPLACE_PENDING 
---


・コンストラクタ-
---
Intent() 
Intent(Intent o) 
Intent(String action) 
Intent(String action, Uri uri) 
Intent(Context packageContext, Class<?> cls) 
Intent(String action, Uri uri, Context packageContext, Class<?> cls)  
---

・主なメソッド
---
Intent         addCategory(String category) 
Intent         addFlags(int flags) 
boolean        filterEquals(Intent other) 
int            filterHashCode() 
String         getAction() 

Set<String>    getCategories() 

ComponentName  getComponent() 
Uri            getData() 
String         getDataString() 

int            getFlags() 

static Intent  getIntent(String uri) 
static Intent  getIntentOld(String uri)  

String         getPackage() 

String         getScheme() 
Intent         getSelector() 

Rect           getSourceBounds() 
String         getType() 
boolean        hasCategory(String category) 
boolean        hasFileDescriptors() 
void           removeCategory(String category) 
void           removeExtra(String name) 
Intent         setAction(String action) 
Intent         setClass(Context packageContext, Class<?> cls) 
Intent         setClassName(Context packageContext, String className) 
Intent         setClassName(String packageName, String className) 
Intent         setComponent(ComponentName component) 
Intent         setData(Uri data) 
Intent         setDataAndType(Uri data, String type) 
Intent         setFlags(int flags) 
Intent         setPackage(String packageName) 
Intent         setType(String type) 
String         toUri(int flags) 
---


・Extra 関係のメソッド
---
xxx[]           getXxxArrayExtra(String name) 
xxx             getXxxExtra(String name, xxx defaultValue) 
    xxx: boolean, byte, char, double, float, int, long, short

ArrayList<Integer>  getIntegerArrayListExtra(String name) 

Yyy[]           getYyyArrayExtra(String name) 
ArrayList<Yyy>  getYyyArrayListExtra(String name) 
Yyy             getYyyExtra(String name) 
    Yyy: CharSequence, String

Parcelable[]                         getParcelableArrayExtra(String name) 
<T extends Parcelable> ArrayList<T>  getParcelableArrayListExtra(String name) 
<T extends Parcelable> T             getParcelableExtra(String name) 

Serializable    getSerializableExtra(String name) 

Bundle          getBundleExtra(String name) 
Bundle          getExtras() 

boolean         hasExtra(String name) 

Intent  putExtra(String name, xxx[] value) 
Intent  putExtra(String name, xxx value) 
    xxx: boolean, byte, char, double, float, int, long, short

Intent  putExtra(String name, Yyy value) 
Intent  putExtra(String name, Yyy[] value) 
Intent  putYyyArrayListExtra(String name, ArrayList<Yyy> value) 
    Yyy: CharSequence, String, Parcelable

Intent  putExtra(String name, Bundle value) 
Intent  putExtra(String name, Serializable value) 

Intent  putExtras(Intent src) 
Intent  putExtras(Bundle extras) 

Intent  putIntegerArrayListExtra(String name, ArrayList<Integer> value) 

Intent  replaceExtras(Bundle extras) 
Intent  replaceExtras(Intent src) 
---


■ マニュフェスト

マニフェストには、2 つのアクティビティ要素が記される。

□ AndroidManifest.xml
---
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="jp.marunomaruno.android.intent"
    android:versionCode="1"
    android:versionName="1.0" >

    <uses-sdk android:minSdkVersion="8" />

    <application
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name" >
        <activity
            android:name=".Intent01Activity"
            android:label="@string/app_name" >    <!-- (1) -->
            <intent-filter>    <!-- (2) -->
                <action android:name="android.intent.action.MAIN" /> <!-- (3) -->
                <category android:name="android.intent.category.LAUNCHER" />
                                                                    <!-- (4) -->
            </intent-filter>
        </activity>
        <activity
            android:name=".OtherActivity"
            android:label="other activity" >
            <intent-filter>
                <action android:name="android.intent.action.SEND" /> <!-- (5) -->
                <category android:name="android.intent.category.DEFAULT" />    
                                                                    <!-- (6) -->
            </intent-filter>
        </activity>
    </application>
</manifest>
---

(1) アクティビティ

    <activity
        android:name=".Intent01Activity"
        android:label="@string/app_name" >    <!-- (1) -->


(2) インテント・フィルター

このクラスがサポートするアクションやカテゴリーについて指定する。

    <intent-filter>    <!-- (2) -->

この要素の子要素として、つぎの要素が指定できる。
    action
    category
    data


(3)(5) アクション

Intent01Activity のアクションを「メインプログラムの起動」にする。これは、アプリ
ケーションが最初に表示するアクティビティを意味する。

    <action android:name="android.intent.action.MAIN" />    <!-- (3) -->


OtherActivity のアクションを「データの送信」にする。

    <action android:name="android.intent.action.SEND" />    <!-- (5) -->

指定できるアクションについては、上記の Intent クラスの定数を参考。
定数 ACTION_xxx の xxx 部分が
android.intent.action.XXX
になる。


(4)(6) カテゴリー

Intent01Activity のカテゴリーを「ランチャー」にする。これは、このアクティビティ
をランチャーで選択できるようにする。

    <category android:name="android.intent.category.LAUNCHER" />    <!-- (4) -->


OtherActivity のカテゴリーを「デフォルト」にする。

    <category android:name="android.intent.category.DEFAULT" />    <!-- (6) -->
      
指定できるカテゴリーについては、上記の Intent クラスの定数を参考。
定数 CATEGORY_xxx の xxx 部分が
android.intent.category.XXX
になる。


■ リソース

□ res/values/strings.xml
---
<?xml version="1.0" encoding="utf-8"?>
<resources>
    <string name="app_name">Intent01</string>
    <string name="explicitButtonLabel">明示的にインテントを起動</string>
    <string name="implicitButtonLabel">暗黙的にインテントを起動</string>
</resources>
---

                                                                            以上


[Java] スッキリわかるJava入門

2012年03月06日 | Java
スッキリわかるJava入門
中山 清喬 (著), 国本 大悟 (著)
http://www.impressjapan.jp/support/aftercare/3086

¥2,730(本体 ¥2,600+税)
単行本(ソフトカバー): 640ページ
出版社: インプレスジャパン (2011/10/7)
言語 日本語
ISBN-10: 4844330861
ISBN-13: 978-4844330868
発売日: 2011/10/7
商品の寸法: 20.8 x 15 x 4.2 cm

第1章 Javaをはじめよう
ようこそJavaの世界へ
Java開発の基礎知識
Javaプログラムの基本構造

第2章 式と演算子
演算子、型の変換
命令実行の文

第3章 条件分岐と繰り返し
条件式の書き方、分岐構文のバリエーション
繰り返し構文のバリエーション

第4章 配列
配列の書き方
多次元の配列

第5章 メソッド
メソッドとは
引数と戻り値の利用
オーバーロード

付録A JDKのインストール

第6章 複数クラスを用いた開発
複数クラスで構成されるプログラム
パッケージに属したクラスの実行方法

第7章 オブジェクト指向をはじめよう
オブジェクト指向を学ぶ理由
オブジェクト指向の全体像と本質

第8章 インスタンスとクラス
クラス定義による効果
インスタンスの利用方法

第9章 さまざまなクラス機構
クラス型と参照
コンストラクタ
静的メンバ

第10章 カプセル化
カプセル化の目的とメリット

第11章 継承
継承の基礎
継承とコンストラクタ

第12章 高度な継承
抽象クラス
インタフェース

第13章 多態性
多態性とは
多態性のメリット

第14章 Javaを支える標準クラス

第15章 例外
エラーの種類と対応策

第16章 まだまだ広がるJavaの世界

付録B エラー解決・虎の巻

付録C JDKバージョンによる違い

[Android] オプション・メニューとコンテキスト・メニュー

2012年03月05日 | Android
[Android] オプション・メニューとコンテキスト・メニュー
================================================================================

オプション・メニューは、実機によっては、画面とは別にある「メニュー」ボタン押下に
よって表示されるコンポーネント。タブレットなどでは、画面上に「メニュー」ボタンが
あったりする。

コンテキスト・メニューは、ビューの部品(たとえば、TextView など)を長押しすること
で、そのコンポーネント上に表示されるメニューである。

メニューは、その項目数が 6 つ以内のときはグリッド表示され、7 つ以上になったとき
は 6 つ目のメニュー項目が「その他」になり、それをクリックすることで、残りのメニ
ューが表示される。


つぎの Activity クラスのメソッドをオーバーライドすることで、オプション・メニュー
を設定する。
public boolean onCreateOptionsMenu(Menu menu)
                オプション・メニュー生成時のハンドラー
public boolean onMenuOpened(int featureId, Menu menu)
                オプション・メニューを開いたときのハンドラー
public void    onOptionsMenuClosed(Menu menu)
                オプション・メニューを閉じたときのハンドラー
public boolean onOptionsItemSelected(MenuItem item)
                オプション・メニューの項目選択時のハンドラー


つぎの Activity クラスのメソッドをオーバーライドすることで、コンテキスト・メニ
ューを設定する。
public void    onCreateContextMenu(ContextMenu menu, View v,
                                                ContextMenuInfo menuInfo)
                コンテキスト・メニュー生成時のハンドラー
public void    onContextMenuClosed(Menu menu)
                コンテキスト・メニューを閉じたときのハンドラー
public boolean onContextItemSelected(MenuItem item)
                コンテキスト・メニューの項目選択時のハンドラー

なお、コンテキスト(ビュー)とこのコンテキスト・メニューとを紐づけるのは、Activity.
registerForContextMenu() メソッドによる。

また、オプション・メニュー、コンテキスト・メニュー共通で、その項目選択時のハンド
ラーとして、次のメソッドがある。
public boolean onMenuItemSelected(int featureId, MenuItem item)


▲ アクティビティ

上記のメソッドをオーバーライドして、その動きを確認している。

□ Menu01Activity.java
---
package jp.marunomaruno.android.menu;

import android.app.Activity;
import android.content.Context;
import android.os.Bundle;
import android.view.ContextMenu;
import android.view.Menu;
import android.view.MenuItem;
import android.view.SubMenu;
import android.view.View;
import android.view.ContextMenu.ContextMenuInfo;
import android.widget.TextView;
import android.widget.Toast;
import jp.marunomaruno.android.menu.R;

public class Menu01Activity extends Activity {
    private static final int TOAST_DURATION = Toast.LENGTH_SHORT;
    private Context context;

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

        // コンテキスト・メニューの設定
        TextView text1 = (TextView) findViewById(R.id.text1);
        registerForContextMenu(text1); // (1)
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) { // (2)
        super.onCreateOptionsMenu(menu); // (3)
        MenuItem item1 = menu.add("アイスクリーム"); // (4)
        MenuItem item2 = menu.add("あられ");
        SubMenu sub3 = menu.addSubMenu("あずき ..."); // (5)
        sub3.add("つぶあん"); // (6)
        sub3.add("こしあん");
        return true; // (7)
    }

    @Override
    public boolean onMenuOpened(int featureId, Menu menu) { // (8)
        String message = String.format(
                "onMenuOpened(): featureId: %d, menu: ¥"%s¥"", featureId, menu);
        Toast.makeText(context, message, TOAST_DURATION).show();
        System.out.println(message);
        return super.onMenuOpened(featureId, menu);
    }

    @Override
    public void onOptionsMenuClosed(Menu menu) { // (9)
        String message = String.format("onOptionsMenuClosed(): menu: ¥"%s¥"",
                menu);
        Toast.makeText(context, message, TOAST_DURATION).show();
        System.out.println(message);
        super.onOptionsMenuClosed(menu);
    }

    @Override
    public boolean onMenuItemSelected(int featureId, MenuItem item) { // (10)
        String message = String.format(
                "onMenuItemSelected(): featureId: %d, item: ¥"%s¥"", featureId,
                item);
        Toast.makeText(context, message, TOAST_DURATION).show();
        System.out.println(message);
        return super.onMenuItemSelected(featureId, item);
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) { // (11)
        String message = String.format("onOptionsItemSelected(): item: ¥"%s¥"",
                item);
        Toast.makeText(context, message, TOAST_DURATION).show();
        System.out.println(message);
        return super.onOptionsItemSelected(item);
    }

    @Override
    public void onCreateContextMenu(ContextMenu menu, View v,
            ContextMenuInfo menuInfo) { // (12)
        menu.setHeaderTitle("Context menu"); // (13)
        MenuItem item1 = menu.add("Apple");
        MenuItem item2 = menu.add("Banana");
        SubMenu sub3 = menu.addSubMenu("Chocolate ...");
        sub3.add("Black");
        sub3.add("White");
    }

    @Override
    public void onContextMenuClosed(Menu menu) { // (14)
        String message = String.format("onContextMenuClosed(): menu: ¥"%s¥"",
                menu);
        Toast.makeText(context, message, TOAST_DURATION).show();
        System.out.println(message);
        super.onContextMenuClosed(menu);
    }

    @Override
    public boolean onContextItemSelected(MenuItem item) { // (15)
        String message = String.format("onContextItemSelected(): item: ¥"%s¥"",
                item);
        Toast.makeText(context, message, TOAST_DURATION).show();
        System.out.println(message);
        return super.onContextItemSelected(item);
    }
}
---

(1) ビューのコンポーネントにコンテキスト・メニューを登録する

テキスト・ビューに対し、コンテキスト・メニューを登録する。

    registerForContextMenu(text1); // (1)


・Activity クラスのメソッド
---
void     registerForContextMenu(View view)
---


(2)(3)(7) オプション・メニューを生成したときの処理

アプリケーション起動時に、オプション・メニューは生成される。

    public boolean onCreateOptionsMenu(Menu menu) { // (2)

onCreateOptionsMenu() の先頭で、スーパークラスのメソッドを実行する。

    super.onCreateOptionsMenu(menu); // (3)

メニューが完成したので、true を返す。

    return true; // (7)


(4) オプション・メニューに項目を追加する

onCreateOptionsMenu() メソッドの引数で、Menu オブジェクトが渡ってくるので、これ
に対し、add() メソッドを使って、メニューの項目を追加する。

    MenuItem item1 = menu.add("アイスクリーム"); // (4)


・Menu に項目を追加する主なメソッド(すべて abstract なので、その記述を省略)
---
MenuItem  add(CharSequence title) 
MenuItem  add(int groupId, int itemId, int order, int titleRes) 
MenuItem  add(int titleRes) 
MenuItem  add(int groupId, int itemId, int order, CharSequence title) 
---
groupId          通常は NONE でよい(グループ化するための項目)
itemId           項目 ID
order            メニュー項目を追加する位置(通常は NONE)
title, titleRes  メニュー項目のテキストの文字列またはリソース ID
---


(5)(6) オプション・メニューにサブ・メニューを追加する

サブ・メニューを追加するには、addSubMenu() メソッドを使う。この返り値は SubMenu 
クラスになる。

    SubMenu sub3 = menu.addSubMenu("あずき ..."); // (5)


・サブ・メニューを追加するメソッド(すべて abstract なので、その記述を省略)
---
SubMenu  addSubMenu(int groupId, int itemId, int order, CharSequence title) 
SubMenu  addSubMenu(int groupId, int itemId, int order, int titleRes) 
SubMenu  addSubMenu(CharSequence title) 
SubMenu  addSubMenu(int titleRes) 
---

addSubMenu() メソッドで作ったサブ・メニューに、add() メソッドを使って項目を追加す
る。
    sub3.add("つぶあん"); // (6)


・サブ・メニューに項目を追加するメソッド(すべて abstract なので、その記述を省略、
メニューに項目を追加するメソッドと同じ)
---
MenuItem  add(CharSequence title) 
MenuItem  add(int groupId, int itemId, int order, int titleRes) 
MenuItem  add(int titleRes) 
MenuItem  add(int groupId, int itemId, int order, CharSequence title) 
---


(8) オプション・メニューを開いたときの処理

onCreateOptionsMenu() メソッドは、アプリケーション起動時に実行されるだけなので、
オプション・メニューが開かれるたびに呼ばれるメソッドがある。

    public boolean onMenuOpened(int featureId, Menu menu) { // (8)


(9) オプション・メニューを閉じたときの処理

    public void onOptionsMenuClosed(Menu menu) { // (9)


(10) メニューの項目を選択したときの処理

このメソッドは、オプション・メニュー、コンテキスト・メニューで共通で使える。
まず、このメソッドが動き、その後、オプション・メニューのときは 
onOptionsItemSelected() メソッドが、コンテキスト・メニューのときは 
onContextItemSelected() メソッドが動く。

引数の item が選択したメニュー項目になる。

    public boolean onMenuItemSelected(int featureId, MenuItem item) { // (10)

featureId は、メニューのパネルの ID。


メニュー項目の情報は、以下のメソッドを使って取得する。

・取得関係の主なメソッド(すべて abstract なので、その記述を省略)
---
int          getItemId() 
int          getOrder() 
SubMenu      getSubMenu() 
CharSequence getTitle() 
CharSequence getTitleCondensed() 
---


(11) オプション・メニューの項目を選択したときの処理

    public boolean onOptionsItemSelected(MenuItem item) { // (11)

MenuItem オブジェクトは、オプション・メニュー項目でも、サブ・メニュー項目でも、コ
ンテキスト・メニュー項目でも同じである。


(12) コンテキスト・メニューを生成したときの処理

オプション・メニューと違い、コンテキスト・メニューを開くたびにこのメソッドが呼ばれ
る。

    public void onCreateContextMenu(ContextMenu menu, View v,
            ContextMenuInfo menuInfo) { // (12)


(13) コンテキスト・メニューのタイトルを設定する

    menu.setHeaderTitle("Context menu"); // (13)


(14) コンテキスト・メニューを閉じたときの処理

    public void onContextMenuClosed(Menu menu) { // (14)


(15) コンテキスト・メニューの項目を選択したときの処理

    public boolean onContextItemSelected(MenuItem item) { // (15)


△ Menu インターフェース

android.view.Menu

オプション・メニュー、コンテキスト・メニューで使うインターフェース。

・主なメソッド(すべて abstract なので、その記述を省略)
---
MenuItem add(CharSequence title) 
MenuItem add(int groupId, int itemId, int order, int titleRes) 
MenuItem add(int titleRes) 
MenuItem add(int groupId, int itemId, int order, CharSequence title) 

SubMenu  addSubMenu(int groupId, int itemId, int order, CharSequence title) 
SubMenu  addSubMenu(int groupId, int itemId, int order, int titleRes) 
SubMenu  addSubMenu(CharSequence title) 
SubMenu  addSubMenu(int titleRes) 

void     clear() 

void     close() 

MenuItem findItem(int id) 
MenuItem getItem(int index) 
boolean  hasVisibleItems() 

void     removeItem(int id) 

int      size()  
---


△ SubMenu インターフェース

android.view.SubMenu

サブメニュー用のインターフェース。サブメニューは、末端のメニューで、この下はメニ
ュー項目しか追加できない。


・主なメソッド(すべて abstract なので、その記述を省略)
---
void     clearHeader()
MenuItem getItem()
SubMenu  setHeaderIcon(Drawable icon)
SubMenu  setHeaderIcon(int iconRes)
SubMenu  setHeaderTitle(CharSequence title)
SubMenu  setHeaderTitle(int titleRes)
SubMenu  setHeaderView(View view)
SubMenu  setIcon(Drawable icon)
SubMenu  setIcon(int iconRes)
---


△ MenuItem インターフェース

android.view.MenuItem

メニュー項目のインターフェース。


・主なメソッド(すべて abstract なので、その記述を省略)
---
int      getItemId() 
ContextMenu.ContextMenuInfo  getMenuInfo() 
int      getOrder() 
SubMenu  getSubMenu() 
CharSequence getTitle() 
CharSequence getTitleCondensed() 
boolean  hasSubMenu() 
boolean  isCheckable() 
boolean  isChecked() 
boolean  isEnabled() 
boolean  isVisible() 
MenuItem setCheckable(boolean checkable) 
MenuItem setChecked(boolean checked) 
MenuItem setEnabled(boolean enabled) 
MenuItem setIcon(Drawable icon) 
MenuItem setIcon(int iconRes) 
MenuItem setOnMenuItemClickListener(MenuItem.OnMenuItemClickListener menuItemClickListener) 
MenuItem setTitle(CharSequence title) 
MenuItem setTitle(int title) 
MenuItem setTitleCondensed(CharSequence title) 
MenuItem setVisible(boolean visible)  
---


△ ContextMenu インターフェース

android.view.ContextMenu

コンテキスト・メニューを使うためには、つぎの手順が必要。
・ロング・クリックするクライアント・オブジェクトに対して
     registerForContextMenu(View)
を行う。
そして、つぎのメソッドをオーバーライドして、メニュー項目を追加する。
     onCreateContextMenu(ContextMenu, View, ContextMenu.ContextMenuInfo)


・主なメソッド(すべて abstract なので、その記述を省略)
---
void         clearHeader() 
ContextMenu  setHeaderIcon(Drawable icon) 
ContextMenu  setHeaderIcon(int iconRes) 
ContextMenu  setHeaderTitle(CharSequence title) 
ContextMenu  setHeaderTitle(int titleRes) 
ContextMenu  setHeaderView(View view)  
---


△ ContextMenuInfo インターフェース

android.view.ContextMenu.ContextMenuInfo

AdapterView などで使うマーカー・インターフェース。
メソッドなどは持っていない。


▲ レイアウト

コンテキスト・メニューを表示するための TextView を定義。

□ res/layout/main.xml
---
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="vertical" >

    <TextView
        android:id="@+id/text1"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:background="#CCCC00"
        android:hint="@string/hint"
        android:text=""
        android:textAppearance="?android:attr/textAppearanceLarge" />
</LinearLayout>
---


▲ リソース

□ res/values/strings.xml
---
<?xml version="1.0" encoding="utf-8"?>
<resources>
    <string name="hint">ここを長押しするとコンテキストメニューが出る</string>
    <string name="app_name">Menu01</string>
</resources>
---


▲ ログ

メニュー関係のハンドラーの動きを確認。

---
○ アプリケーション起動時
onCreateOptionsMenu(): menu: "MenuBuilder@46c02638"

○ オプション・メニュー選択時
onMenuOpened(): featureId: 0, menu: "MenuBuilder@46c02638"
onMenuItemSelected(): featureId: 0, item: "アイスクリーム"
onOptionsItemSelected(): item: "アイスクリーム"
onOptionsMenuClosed(): menu: "MenuBuilder@46c02638"

○ オプション・メニューで、サブ・メニュー選択時
onMenuOpened(): featureId: 0, menu: "MenuBuilder@46c02638"
onMenuItemSelected(): featureId: 0, item: "あずき ..."
onOptionsItemSelected(): item: "あずき ..."
onMenuItemSelected(): featureId: 0, item: "つぶあん"
onOptionsItemSelected(): item: "つぶあん"

○ コンテキスト・メニュー選択時
onCreateContextMenu(): menu: "ContextMenuBuilder@46c2f3d0"
onMenuItemSelected(): featureId: 6, item: "Banana"
onContextItemSelected(): item: "Banana"
onContextMenuClosed(): menu: "ContextMenuBuilder@46c2f3d0"

○ コンテキスト・メニューで、サブ・メニュー選択時
onCreateContextMenu(): menu: "ContextMenuBuilder@46c43598"
onMenuItemSelected(): featureId: 6, item: "Chocolate ..."
onContextItemSelected(): item: "Chocolate ..."
onMenuItemSelected(): featureId: 6, item: "White"
onContextItemSelected(): item: "White"
onContextMenuClosed(): menu: "SubMenuBuilder@46c44618"
---
※パッケージ名 "com.android.internal.view.menu." の部分は表示から割愛
                                                                            以上



Eclipseで学ぶはじめてのJava 第2版(DVD付)

2012年03月04日 | Java
Eclipseで学ぶはじめてのJava 第2版(DVD付) [大型本]
木村 聡 (著)
http://www.sbcr.jp/products/4797359039.html

大型本: 472ページ
出版社: ソフトバンククリエイティブ; 第2版 (2010/4/30)
ISBN-10: 479735903X
ISBN-13: 978-4797359039
発売日: 2010/4/30
商品の寸法: 23 x 18.4 x 3 cm

SECTION 1 基礎編

第1章 プログラムについて
第2章 まずは、実行してみる
第3章 Eclipseを使う
第4章 いろいろ表示してみる

●SECTION 2 文法編

第5章 計算してみる
第6章 もし~だったら
第7章 まとまりを持ったデータを扱う
第8章 同じ処理を繰り返す
第9章 これまでのコードを改善する
第10章 クラスを利用する
第11章 コメントとコーディング規約

●SECTION 3 発展編

第12章 オブジェクト指向
第13章 クラスを拡張する
第14章 抽象クラス
第15章 インターフェース
第16章 クラスライブラリを使う
第17章 例外
第18章 アノテーション
第19章 テスト
第20章 デバッグ

付録A プログラミングの準備・セットアップ
付録B クイズの解答
付録C その他の情報

[Android] 標準ウィジェット(1) EditText

2012年03月03日 | Android
                                                                2012-03-09 更新
                                                                2012-03-03 新規
[Android] 標準ウィジェット(1) EditText
================================================================================

Android で文字列データを入力するには、EditText を使う。

この EditText には、いろいろな入力形式が用意されている。
数字だけに限定することもできれば、email で使う文字だけに限定する、また、パスワー
ドの入力に使う、ということも可能。

入力した文字列は
    Editable   getText() 
メソッドを使うが、返り値は Editable 型。通常は toString() メソッドを使って、テキ
ストにして使う。

レイアウトの EditText 要素の android:inputType 属性を使ってこれらを制御する。

------------------- ------------------------------------------------------------
android:inputType 属性
------------------- ------------------------------------------------------------
指定値              動作
none                入力不可になります。
text                文字
textCapCharacters   すべて大文字
textCapWords        単語の先頭を大文字
textCapSentences    文章の先頭を大文字
textAutoCorrect     文字のスペルミスを自動で修正する
textAutoComplete    文字の補完入力する
textMultiLine       文字を複数行入力する
textImeMultiLine    通常の文字入力時は複数行入力を許可せず、
                    IMEによって複数行入力を設定
textUri             URL
textEmailAddress    メールアドレス
textEmailSubject    メールの件名
textShortMessage    ショートメッセージ
textLongMessage     ロングメッセージ
textPersonName      人名
textPostalAddress   住所
textPassword        パスワード入力
textVisiblePassword パスワード入力(パスワードは表示)
textWebEditText     HTML
textFilter          他のデータでフィルタされた文字
textPhonetic        発音表記
number              数値入力
numberSigned        符号付きの数値
numberDecimal       小数入力
phone               電話番号
datetime            日付時刻
date                日付
time                時刻
------------------- ------------------------------------------------------------

参考:
Android Wiki* UIコンポーネント/TextView
http://wikiwiki.jp/android/?UI%A5%B3%A5%F3%A5%DD%A1%BC%A5%CD%A5%F3%A5%C8%2FTextView#inputType


▲ レイアウト

上記のうちのつぎの属性値を確認する。
    textPassword
    textEmailAddress
    textMultiLine
    date
    number

なお、 android:inputType 属性を指定していない場合もあわせて確認する。

□ res/layout/main.xml
---
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="vertical" >

    <!-- (1) 通常のテキスト -->

    <EditText
        android:id="@+id/editText1"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:hint="文字列" >

        <requestFocus /> <!-- (7) -->
    </EditText>

    <!-- (2) パスワード -->

    <EditText
        android:id="@+id/password"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:hint="password"
        android:inputType="textPassword" />

    <!-- (3) email アドレス -->

    <EditText
        android:id="@+id/emailAddress"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:hint="email address"
        android:inputType="textEmailAddress" />

    <!-- (4) 複数行 -->

    <EditText
        android:id="@+id/multilineText"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:hint="Multiline text"
        android:inputType="textMultiLine" />

    <!-- (5) 日付 -->

    <EditText
        android:id="@+id/date"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:hint="date"
        android:inputType="date" />

    <!-- (6) 数値 -->

    <EditText
        android:id="@+id/number"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:hint="number"
        android:inputType="number" />

    <Button
        android:id="@+id/button1"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:onClick="onClickHandler"
        android:text="@string/submit" />

    <TextView
        android:id="@+id/text1"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:text=""
        android:textAppearance="?android:attr/textAppearanceLarge" />

</LinearLayout>
---

▲ リソース

□ res/values/strings.xml
---
<?xml version="1.0" encoding="utf-8"?>
<resources>
    <string name="app_name">TextField01</string>
    <string name="submit">クリック</string>
</resources>
---


▲ アクティビティ

□ TextField01Activity.java
---
package jp.marunomaruno.android.textfield;

import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
import jp.marunomaruno.android.textfield.R;

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

    public void onClickHandler(View view) {
        EditText edit1 = (EditText) findViewById(R.id.editText1);
        EditText password = (EditText) findViewById(R.id.password);
        EditText emailAddress = (EditText) findViewById(R.id.emailAddress);
        EditText multilineText = (EditText) findViewById(R.id.multilineText);
        EditText date = (EditText) findViewById(R.id.date);
        EditText number = (EditText) findViewById(R.id.number);

        String text = String
                .format(" edit1=%s%n password=%s%n emailAddress=%s%n 
									multilineText=%s%n date=%s%n number=%s%n",
                        edit1.getText(), password.getText(), emailAddress
                                .getText(), multilineText.getText(), date
                                .getText(), number.getText());
        Toast.makeText(this, text, Toast.LENGTH_LONG).show();

        TextView text1 = (TextView) findViewById(R.id.text1);
        text1.setText(text);
    }
}
---

△ EditText クラス

java.lang.Object 
   +  android.view.View 
     +  android.widget.TextView 
       +  android.widget.EditText 

ユーザーからの入力をサポートするためのクラス。
レイアウトでは、android:inputType 属性をつけることで、入力値を制限することができ
る。
特徴としては、getText() メソッドの返り値の型が Editable 型である。
String 型として、入力した値を取得するには、この返り値のオブジェクトの toString()
 メソッドを使って取得する必要がある。

・主なメソッド
---
Editable   getText() 
void       setText(CharSequence text, TextView.BufferType type)  

void       selectAll() 
void       setEllipsize(TextUtils.TruncateAt ellipsis) 
void       extendSelection(int index) 
void       setSelection(int index) 
void       setSelection(int start, int stop) 

void       setFilters(InputFilter[] filters)
final void setHint(CharSequence hint)
final void setHint(int resid)
void       setKeyListener(KeyListener input)
void       setHorizontallyScrolling(boolean whether)
void       setHeight(int pixels)
void       setWidth(int pixels)
---


△ Editable インターフェース

android.text.Editable

テキスト操作に関するインターフェース。
実際に使うためには、toString() メソッドで、テキストにしてから使う場合が多い。


★疑問
---
EditText の getText() はなぜ Editable 型で返すんだろうか? スーパークラスの 
TextView は CharSequence なのに。CharSequence は、String でも StringBuilder でも
いいので納得できるが。。
---


■ EditView で、最初からソフトウェアキーボードを表示しておく方法 (2012-03-09 追記)

レイアウトか Activity クラスで、目的の EditText にフォーカスを当てておく。
マニフェストの activity 要素で、android:windowSoftInputMode="stateVisible" 属性をつける。


□ レイアウト

---
    <EditText
        ... >
        <requestFocus /> <!-- <= これを指定 -->
    </EditText>
---


□ Activity クラス

---
    EditText editText = new EditText(this);
    editText.requestFocus();    // <= フォーカスを当てる(XML での指定でもよい)
---


□ AndroidManifest.xml

activity 要素に android:windowSoftInputMode 属性を追加

---
    <activity android:name=".XxxActivity"
              android:label="@string/app_name"
              android:windowSoftInputMode="stateVisible">  // <= これで表示される
        <intent-filter>
            <action android:name="android.intent.action.MAIN" />
            <category android:name="android.intent.category.LAUNCHER" />
        </intent-filter>
    </activity>
---

                                                                        以上