Android: OnDraw and associate the class with the ImageView in the xml
I'm trying to override the default drawing for a particular ImageView in my XML layout file.
All the examples, I've seen do this using setContentView in the activity. I want to leave the main content view alone, and just handle the drawing for the one image control. I'm at a loss on how to associate the id of the imageview with the new instantiated class to handle the OnDraw.
I may very well be going about this backwards, so any help is appreciated.
as in below:
littleImage = (ImageView) findViewById(R.id.myImageView);
Vi开发者_Go百科ew myView = new MyCustomView(littleImage.getContext());
// NO! NO! I want to leave the 'main' view alone
//setContentView(myView);
public void test()
{
littleImage.invalidate();
}
the layout
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="wrap_content"
android:layout_height="fill_parent"
>
<TextView android:id="@+id/label_title"
android:layout_width="320dip"
android:layout_height="wrap_content"
android:text="@string/app_name"
android:textSize="20sp"
android:gravity="center_horizontal"
android:background="#6B8AAD"
/>
<ImageView
android:id="@+id/image"
android:clickable="false"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:scaleType="fitCenter"
/>
<ImageView
android:id="@+id/myImageView"
android:clickable="false"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:scaleType="fitCenter"
android:visibility="invisible"
/>
</LinearLayout>
As you see, I've tried the imageViews getContext, but that didn't help. How can I get this to trigger OnDraw?
The best way to achieve this is by creating a class LittleImage that Extends ImageView
public class LittleImage extends ImageView
{
public LittleImage(Context context, AttributeSet attrs)
{
super(context, attrs);
}
@Override
public void onDraw(Canvas canvas)
{
// Do you custom drawing here...
}
}
Than, in your xml layout you can use:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="wrap_content"
android:layout_height="fill_parent">
<TextView android:id="@+id/label_title"
android:layout_width="320dip"
android:layout_height="wrap_content"
android:text="@string/app_name"
android:textSize="20sp"
android:gravity="center_horizontal"
android:background="#6B8AAD"/>
<ImageView
android:id="@+id/image"
android:clickable="false"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:scaleType="fitCenter"
/>
<com.yourpackage.LittleImage
android:id="@+id/myImageView"
android:clickable="false"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:scaleType="fitCenter"
android:visibility="invisible"
/>
</LinearLayout>
精彩评论