【问题标题】:How to read android:src in my custom component如何在我的自定义组件中读取 android:src
【发布时间】:2012-04-12 18:08:57
【问题描述】:

我正在尝试创建一个继承自 RelativeLayout 的自定义组件。

在我的 xml 布局文件中,我有:

<Mycomponent 
    android:src="@drawable/my_test_image">
      <TestView>
</Mycomponent>

我的问题是如何在 Mycomponent 的构造函数中创建一个 Drawable 类?

我曾尝试阅读 ImageView 的源代码,但似乎尝试了一些 android Internal.R 。

无论如何我可以在我的代码中做到这一点。

谢谢。

【问题讨论】:

  • 你想在自定义视图的构造函数中获取可绘制的my_test_image吗?
  • 是的。我想通过读取布局 xml 文件中的“android:src”来创建一个 Drawable 对象。

标签: android custom-component


【解决方案1】:

我认为 Luksprog 是错误的,我有一个简单的解决方案来访问您的自定义组件“src”数据而无需样式化,只需调用 AttributeSet:

attrs.getAttributeResourceValue("http://schemas.android.com/apk/res/android", "src", 0);

这里你可以看到我的例子,让位图尺寸更便宜,jeje。

public CustomView(Context context, AttributeSet attrs) {
 super(context, attrs);
 int src_resource = attrs.getAttributeResourceValue("http://schemas.android.com/apk/res/android", "src", 0);
 this.setImageBitmap(getDrawable(getResources(),src_resource));
}

public static Bitmap getDrawable(Resources res, int id){
    return BitmapFactory.decodeStream(res.openRawResource(id));
}

现在您将在 xml 中包含如下内容:

<com.example.com.jfcogato.mycomponent.CustomView
    android:id="@+id/tAImageView1"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content" 
    android:src="@drawable/big_image_example"/>

【讨论】:

  • this.setImageDrawable(getResources().getDrawable(src_resource)) ... 应该用于支持所有类型的可绘制对象。您的代码仅支持图片。
【解决方案2】:

我也看到了你可以这样做的建议......

    int attributeIds[] = { android.R.attr.src };
    TypedArray a = context.obtainStyledAttributes(attributeIds);
    int resourceId = a.getResourceId(0, 0);
    a.recycle();

根据我的经验,这段代码可以编译,但在运行时返回 0。

所以是的......请使用上面 jfcogato 的答案。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-08-19
    • 2023-03-04
    • 2012-01-07
    • 2013-09-13
    • 1970-01-01
    相关资源
    最近更新 更多