difficulty using AttributeSet.getAttributeIntValue()
My app needs the height and width of the extended ImageView. I tho开发者_StackOverflowught this should work:
package my.android.test;
public class TestImageView extends ImageView
{
private int mWidth=0;
private int mHeight=0;
public TestImageView(Context context, AttributeSet as)
{
super(context, as);
final String xmlns="http://schemas.android.com/apk/res/android";
mWidth = as.getAttributeIntValue(xmlns, "layout_width", 0);
mHeight = as.getAttributeIntValue(xmlns, "layout_height", 0);
}
@Override
protected void onDraw(Canvas canvas)
{
//do stuff
}
}
but it doesn't work. 0 is returned by getAttributeIntValue() eventhough the layout_height is defined in the layout XML:
<?xml version="1.0" encoding="utf-8"?>
<ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:fillViewport="true"
android:background="#fffcb95a"
<LinearLayout android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
<FrameLayout android:layout_width="fill_parent"
android:layout_height="wrap_content"
<RelativeLayout android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:padding="6dip"
<my.android.test.TestImageView
android:id="@+id/TestImageViewID"
android:layout_width="100dip"
android:layout_height="100dip"
android:src="@drawable/icon"
android:scaleType="centerCrop" />
</RelativeLayout
</FrameLayout
</LinearLayout
</ScrollView
what to do ?
Note an explanation for why the original attempt doesn't work -- layout_width and layout_height are not actually holding integers, they are holding dimensions. You need to retrieve these via Context/Theme.obtainStyledAttributes, so you can get them as a TypedValue that can be converted to pixels.
Just call getWidth()
and getHeight()
.
精彩评论