我在扩展View类时遇到问题,XML正常运行,因为我已经尝试使用ImageView,但不能使用我的自定义类...
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(在res / drawable-mdpi文件夹中)
<?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>
主要活动
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);
}
}
谢谢!
答案 0 :(得分:2)
LayerDrawable是Drawable的子类,因此您仍需要将drawable分配给View。
我建议BubbleView为您的自定义类扩展ImageView而不是View。通过这种方式,您可以在主要活动中以任何布局重复使用drawable。
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 */
}
}
有帮助吗?
答案 1 :(得分:0)
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);}