【发布时间】:2014-04-29 15:50:29
【问题描述】:
这是我主要的 xml 布局的一部分。我有一个复合视图(SingleDrinkView),我想为每个“SingleDrinkView”的图像按钮设置不同的 src。
<LinearLayout
android:layout_width="fill_parent"
android:layout_height="100dp"
android:layout_below="@id/profilePhoto"
android:background="#d0d0d0"
android:orientation="horizontal" >
<com.ziepa.drinkparty.SingleDrinkView
android:layout_width="0dp"
android:layout_height="fill_parent"
android:layout_weight="1"
custom:drinkImage="@drawable/beer_icon"
/>
<com.ziepa.drinkparty.SingleDrinkView
android:layout_width="0dp"
android:layout_height="fill_parent"
android:layout_weight="1"
custom:drinkImage="@drawable/shot_icon"
/>
<com.ziepa.drinkparty.SingleDrinkView
android:layout_width="0dp"
android:layout_height="fill_parent"
android:layout_weight="1"
custom:drinkImage="@drawable/wine_icon"
/>
</LinearLayout>
我添加了一个自定义属性,但我想不出一种方法将它设置为我的图像按钮:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent" >
<ImageButton
android:id="@+id/singleDrinkImage"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:background="@null"
android:padding="0dp"
android:scaleType="centerInside"
android:src="???" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerInParent="true"
android:text="x0"
android:textColor="#000"
android:textSize="32sp" />
</RelativeLayout>
所以我最终尝试通过获取此自定义属性来通过代码设置它:
case R.styleable.SingleDrinkView_drinkImage:
//This string contains "res/drawable-xhdpi/beer_icon.png"
String drinkImage = a.getString(attr);
ImageButton imageBt = (ImageButton) this.findViewById (R.id.singleDrinkImage);
//createFromPath returns null.
imageBt.setImageDrawable(Drawable.createFromPath(drinkImage));
break;
因此我现在不知道该怎么做,我也不确定是否有更聪明的方法。可以这么说,我想拥有具有不同“可设置”属性的相同自定义小部件。
【问题讨论】:
-
你的方法是我通常做的。究竟是什么不工作?
-
我无法设置 imageBt drawable。路径看起来不错,但 createFromPath 返回 null,因此没有设置图像。
标签: android