【问题标题】:Need the image id from xml attributes custom widget需要来自 xml 属性自定义小部件的图像 id
【发布时间】:2012-08-08 03:45:44
【问题描述】:

我有一个自定义控件(现在非常简单),就像一个按钮。它需要显示未按下和按下的图像。它在活动中出现多次,并且根据使用的位置具有不同的图像对。想想工具栏图标 - 与此类似。

这是我的布局的摘录:

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

【问题讨论】:

    标签: android android-drawable custom-widgets android-custom-attributes


    【解决方案1】:

    如果您想获得可绘制对象,请使用TypedArray.getDrawable()。在您的示例中,您使用的是 getString()。

    在你的declare-styleable 使用

       <attr name="srcPressed" format="reference" /> 
    

    【讨论】:

    • 这是有道理的。但是,如何让 id 传递给 getDrawable?我尝试了 a.getDrawable (R.attr.srcPressed),但失败并出现异常。
    • 你是如何声明你的属性(declare-styleable)的?
    • 请看上面;我添加到 xml 块并添加 attrs.xml
    • 是的!这样可行。我想我还没有在 attrs.xml 上找到足够的文档;将继续阅读。 (对于这篇文章的未来查看者,我已经用工作代码更新了原始帖子。)
    【解决方案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 );
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-07-09
      • 2011-04-25
      • 1970-01-01
      • 1970-01-01
      • 2019-03-26
      • 1970-01-01
      相关资源
      最近更新 更多