findViewByIdメソッド

android.appActivityクラス

findViewByIdとは?

 状態:-  閲覧数:4,424  投稿日:2013-04-19  更新日:2013-07-20  
android.appパッケージにあるActivityクラス」のpublicメソッド


機能


引数にリソースIDを指定すると、対応するViewオブジェクトを返す
・「ビューに対して割り当てられたリソースID」から、対応するビューオブジェクトを取得(リソースIDから、GUIオブジェクトを取得)

メソッド仕様

 閲覧数:397 投稿日:2013-04-19 更新日:2014-01-16 

引数


・別途XMLファイルで作成したレイアウトを表すIDを指定
findViewById(R.id.★★)


戻り値


Viewオブジェクト
・直接インスタンスオブジェクトを作成するのではなく、Activityクラスからそのインスタンスオブジェクトを受け取る
Button button = new Button(this)//オブジェクト生成する必要はない
button.findViewById(R.id.★★);

(Button) findViewById(R.id.★★);//返り値として対応するViewオブジェクトを受け取るので、いきなり利用可能



キャストが必要


・返り値として対応するViewオブジェクトを受け取るが、Viewオブジェクトには「Button」「TextView」など様々な種類があるので、明示する必要がある
(Button) findViewById(R.id.★★);//(Button) キャスト
(TextView) findViewById(R.id.★★);//(TextView) キャスト


具体的な実装例

 閲覧数:405 投稿日:2013-04-19 更新日:2013-07-20 

実装例1


「ビューに対して割り当てられたリソースID」とは、下記の場合「main.xml」に記載された「Button1」を指す

▼/src/パッケージ名/MainActivity.java
public class MainActivity extends Activity {

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
       setContentView(R.layout.main);//レイアウト用XMLファイルを設定
       // ダイアラーボタンを押下したとき
       Button dialButton = (Button) findViewById(R.id.Button1);


・レイアウト用XMLファイル
▼/res/layout/main.xml
    <Button android:id="@+id/Button1"
           android:layout_width="fill_parent"
           android:layout_height="wrap_content"
           android:text="ダイアラー起動" />



実装例2


▼/src/com/fc2/blog98/andromaker/housekeepingbook/HousekeepingBook.java
		setContentView(R.layout.main);

/* 変数の設定 */
       int[] calendar=intentCalendar();

       /* コンポーネントの設定 */
       monthButton = (Button)this.findViewById(R.id.monthButton);
       dateButton = (Button)this.findViewById(R.id.dateButton);
       addButton = (Button)this.findViewById(R.id.addButton);
       deleteButton = (Button)this.findViewById(R.id.deleteButton);
       sumText=(TextView)this.findViewById(R.id.sumText);


▼/res/layout/main.xml
    <Button
       android:id="@+id/monthButton"
       android:layout_width="120px"
       android:layout_height="wrap_content"
       android:text="@string/btn_label1"
       />
   <Button
       android:id="@+id/dateButton"
       android:layout_width="200px"
       android:layout_height="wrap_content"
       android:layout_marginLeft="20.0px"
       />
   <Button
       android:id="@+id/addButton"
       android:layout_width="80px"
       android:layout_height="wrap_content"
       android:background ="@android:drawable/ic_menu_add"
       android:layout_marginLeft="20.0px"
       />

		    <Button
       android:id="@+id/deleteButton"
       android:layout_width="200px"
       android:layout_height="wrap_content"
       android:text="一括削除"
       />
        <TextView
android:id="@+id/sumText"
       android:layout_width="wrap_content"
       android:layout_height="wrap_content"
       android:layout_marginLeft="10.0px"
/>



setContentViewメソッド

コメント投稿(ログインが必要)