1)在View类中定义。通过构造函数中引入的AttributeSet 去查找XML布局的属性名称,然后找到它对应引用的资源ID去找值。
案例:实现一个带文字的图片(图片、文字是onDraw方法重绘实现)
public class MyView extends View { private String mtext; private int msrc; public MyView(Context context) { super(context); } public MyView(Context context, AttributeSet attrs) { super(context, attrs); int resourceId = 0; int textId = attrs.getAttributeResourceValue(null, "Text",0); int srcId = attrs.getAttributeResourceValue(null, "Src", 0); mtext = context.getResources().getText(textId).toString(); msrc = srcId; } @Override protected void onDraw(Canvas canvas) { Paint paint = new Paint(); paint.setColor(Color.RED); InputStream is = getResources().openRawResource(msrc); Bitmap mBitmap = BitmapFactory.decodeStream(is); int bh = mBitmap.getHeight(); int bw = mBitmap.getWidth(); canvas.drawBitmap(mBitmap, 0,0, paint); //canvas.drawCircle(40, 90, 15, paint); canvas.drawText(mtext, bw, bh, paint); } }
布局文件:
<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical" > <com.example.myimageview2.MyView android:id="@+id/myView1" android:layout_width="wrap_content" android:layout_height="wrap_content" Text="@string/hello_world" Src="@drawable/xh"/> </LinearLayout>