4

ボタンのようなカスタム コントロール (今のところ非常に単純) があります。プレスされていない画像とプレスされた画像を表示する必要があります。アクティビティで複数回表示され、使用される場所に応じて異なる画像のペアがあります。ツールバーのアイコンを考えてみてください - それに似ています。

これが私のレイアウトの抜粋です:

<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;
  }
}
4

2 に答える 2

8

ドローアブルを取得する場合は、TypedArray.getDrawable()を使用します。あなたの例では、getString() を使用しています。

declare-styleable利用にあたって

   <attr name="srcPressed" format="reference" /> 
于 2012-08-10T23:10:15.327 に答える
2

完全に解決された Drawable 自体ではなく、Drawable の実際のリソース ID が必要な場合は、次のようにします。

TypedArray a = context.obtainStyledAttributes( attrs, R.styleable.FooLayout );
TypedValue value = new TypedValue();
a.getValue( R.styleable.FooLayout_some_attr, value );
Log.d( "DEBUG", "This is the actual resource ID: " + value.resourceId );
于 2014-09-26T22:02:16.200 に答える