ボタンのようなカスタム コントロール (今のところ非常に単純) があります。プレスされていない画像とプレスされた画像を表示する必要があります。アクティビティで複数回表示され、使用される場所に応じて異なる画像のペアがあります。ツールバーのアイコンを考えてみてください - それに似ています。
これが私のレイアウトの抜粋です:
<TableLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:MyApp="http://schemas.android.com/apk/res/com.example.mockup"
android:layout_width="fill_parent"
android:layout_height="fill_parent" >
<TableRow>
<com.example.mockup.ImageGestureButton
android:id="@+id/parent_arrow"
android:src="@drawable/parent_arrow"
MyApp:srcPressed="@drawable/parent_arrow_pressed"
... />
...
</TableRow>
</TableLayout>
attrs.xml:
<?xml version="1.0" encoding="utf-8"?>
<resources>
<declare-styleable name="ImageGestureButton">
<attr name="srcPressed" format="reference" />
</declare-styleable>
</resources>
そして、R.java には次のようなものがあります。
public static final class drawable {
public static final int parent_arrow=0x7f020003;
public static final int parent_arrow_pressed=0x7f020004;
...
}
ウィジェットのインスタンス化中に、アクティビティ xml で宣言された ID を確認したいと考えています。それ、どうやったら出来るの?私はこれを試しました(元の投稿を作業コードで更新したため、次のように機能します。)
public class ImageGestureButton extends ImageView
implements View.OnTouchListener
{
private Drawable unpressedImage;
private Drawable pressedImage;
public ImageGestureButton (Context context, AttributeSet attrs)
{
super(context, attrs);
setOnTouchListener (this);
unpressedImage = getDrawable();
TypedArray a = context.obtainStyledAttributes (attrs, R.styleable.ImageGestureButton, 0, 0);
pressedImage = a.getDrawable (R.styleable.ImageGestureButton_srcPressed);
}
public boolean onTouch (View v, MotionEvent e)
{
if (e.getAction() == MotionEvent.ACTION_DOWN)
{
setImageDrawable (pressedImage);
}
else if (e.getAction() == MotionEvent.ACTION_UP)
{
setImageDrawable (unpressedImage);
}
return false;
}
}