Android ImageButtonセレクターの例
last Android tutorialでは、「ImageButton
」を使用して、カスタマイズされた背景画像で「Button
」を簡単に表示します。 ただし、単純な画像以上のことができます。Androidでは、ボタンがフォーカスされている、ボタンが押されているなど、さまざまな状態に応じてボタンの画像を変更できます。
この例は、このAndroid custom buttonの記事から参照されていますが、わずかな変更が加えられています。
P.S This project is developed in Eclipse 3.7, and tested with Android 2.3.3.
1. リソースに画像を追加する
ボタンの状態に合わせて3つの画像を準備し、「resource/drawable」フォルダーに配置します。
-
button_normal_green.png –デフォルトの画像ボタン。
-
button_focused_orange.png –ボタンがフォーカスされているとき、たとえば、電話のキーパッドがこのボタン上で移動(フォーカス)されているときに表示します。
-
button_pressed_yellow.png –ボタンが押されたときに表示されます。
2. さまざまなボタンの状態にセレクターを追加する
ここで、「res/drawable/」フォルダーに新しいXMLファイルを作成します。任意の名前で、この場合は「new_button.xml
」という名前を付けます。 このファイルは、どのボタン状態がどの画像に属するかを定義しました。
これで、このID:@drawable/new_button
を介してこのボタンを参照できます。
ファイル:res / drawable / new_button.xml
3. 追加ボタン
「res/layout/main.xml」ファイルを開き、通常のボタンを追加し、「android:background="@drawable/new_button
」を介して上記の「new_button」に背景画像を添付します
ファイル:res / layout / main.xml
4. コードコード
単純なクリックリスナーを持つ通常のボタン。
ファイル:MyAndroidAppActivity.java
package com.example.android; import android.app.Activity; import android.os.Bundle; import android.widget.Button; import android.widget.Toast; import android.view.View; import android.view.View.OnClickListener; public class MyAndroidAppActivity extends Activity { Button imageButton; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); addListenerOnButton(); } public void addListenerOnButton() { imageButton = (Button) findViewById(R.id.imageButtonSelector); imageButton.setOnClickListener(new OnClickListener() { @Override public void onClick(View arg0) { Toast.makeText(MyAndroidAppActivity.this, "ImageButton (selector) is clicked!", Toast.LENGTH_SHORT).show(); } }); } }
5. Demo
アプリケーションを実行してください。
1. 結果、デフォルトのボタン。 (button_normal_green.png)
2. ボタンにフォーカスがあります。 (button_focused_orange.png)
3. ボタンが押されています。 (button_pressed_yellow.png)
ソースコードをダウンロード
ダウンロード–Android-ImageButton-Selector-Example.zip(23 KB)