I'm having an issue while extending the View class, the XML works properly as i've tried it with an ImageView, but not with my custom class...
BubbleView.java
import android.content.Context;
import android.content.res.Resources;
import android.graphics.Canvas;
import android.graphics.drawable.LayerDrawable;
import android.view.View;
public class BubbleView extends View {
LayerDrawable rootBubble;
public BubbleView(Context context) {
super(context);
Resources res = this.getResources();
rootBubble开发者_开发百科 = (LayerDrawable) res.getDrawable(R.drawable.bubble);
}
@Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
rootBubble.draw(canvas);
}
}
bubble.xml (in res/drawable-mdpi folder)
<?xml version="1.0" encoding="utf-8"?>
<layer-list xmlns:android="http://schemas.android.com/apk/res/android">
<item>
<shape
android:shape="rectangle">
<solid android:color="#FFFF0000" />
<size android:width="100px" android:height="100px" />
<padding android:bottom="1dp"/>
</shape>
</item>
<item>
<shape
android:shape="oval">
<solid android:color="#FFFFFFFF" />
<size android:width="100px" android:height="100px" />
</shape>
</item>
</layer-list>
main activity
public class VisualManagerActivity extends Activity {
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
LinearLayout main = new LinearLayout(this);
main.addView(new BubbleView(this));
setContentView(main);
}
}
thanks!
LayerDrawable is a subclass of Drawable, therefore you still need to assign your drawable to a View.
I would recommend that BubbleView extends ImageView instead of View for your custom class. This way you can reuse your drawable in any layout you want, as you do in your main activity.
public class BubbleView extends ImageView {
public BubbleView(Context context) {
super(context);
init( context );
}
public BubbleView(Context context, AttributeSet attrs) {
super(context, attrs);
init( context );
}
public BubbleView(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
init( context );
}
private void init(Context context){
Resources res = this.getResources();
setImageDrawable(res.getDrawable(R.drawable.bubble));
/* Any other initialization */
}
@Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
/* Any other drawing functionality */
}
}
Does it help?
protected void onDraw(Canvas canvas)
{
super.onDraw(canvas);
paint = new Paint();
paint.setColor(Color.WHITE);
Rect bounds = new Rect();
paint.getTextBounds(name, 0, name.length(), bounds);
LayerDrawable layerDrawable = (LayerDrawable) resources.getDrawable(R.drawable.your_drawble);
Bitmap b = Bitmap.createBitmap(getWidth(), getHeight(), Bitmap.Config.ARGB_8888);
layerDrawable.setBounds(0, 0, getWidth(), getHeight());
layerDrawable.draw(new Canvas(b));
canvas.drawBitmap(b,0,0,paint);}
精彩评论