从xml属性自定义小部件中获取图像id

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;
  }
}
2个回答

8
如果您想获取drawable,请使用TypedArray.getDrawable()。在您的示例中,您正在使用getString()。
在您的declare-styleable中使用
   <attr name="srcPressed" format="reference" /> 

这很有道理。但是,我该如何获取ID以传递给getDrawable?我尝试使用a.getDrawable(R.attr.srcPressed),但出现了异常。 - Peri Hartman
你是如何声明你的属性(declare-styleable)的? - Diego Torres Milano
请看上面;我添加了xml块并添加了attrs.xml。 - Peri Hartman
太好了!那个可行。我想我还没有找到关于attrs.xml的足够文档,我会继续阅读。(对于这篇文章的未来读者,我已经更新了原始帖子,加入了可行的代码。) - Peri Hartman

2
如果您想获取Drawable的实际资源ID,而不是完全解析的Drawable本身,可以这样做:
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 );

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接