我正在逐字逐句地使用 shapedrawable 示例(几乎),但似乎无法在 xml 中调用 shapedrawable 类。文档所述的唯一额外步骤是重写 View(Context, AttributeSet),我想我做到了。我指的文档在这里:http://developer.android.com/guide/topics/graphics/2d-graphics.html这是我的代码。
安卓测试.java
package com.android.test;
import android.app.Activity;
import android.os.Bundle;
public class AndroidTest extends Activity {
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
}
}
ShapeSquare.java
package com.android.test;
import android.content.Context;
import android.graphics.Canvas;
import android.graphics.drawable.ShapeDrawable;
import android.graphics.drawable.shapes.OvalShape;
import android.util.AttributeSet;
import android.view.View;
public class ShapeSquare extends View {
private ShapeDrawable mDrawable;
public ShapeSquare(Context context, AttributeSet attrs) {
super(context, attrs);
int x = 10;
int y = 10;
int width = 300;
int height = 50;
mDrawable = new ShapeDrawable(new OvalShape());
mDrawable.getPaint().setColor(0xff74AC23);
mDrawable.setBounds(x, y, x + width, y + height);
}
protected void onDraw(Canvas canvas) {
mDrawable.draw(canvas);
}
}
主.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
>
<com.android.test.shapedrawable.ShapeSquare
android:layout_width="fill_parent"
android:layout_height="wrap_content"
/>
</LinearLayout>
错误是强制退出错误,我无法弄清楚问题出在哪里。形状属性将由用户输入决定(最终),因此形状需要在类中创建,而不是在所有 xml 中创建。
最佳答案
解决了这里的问题。我不得不从以下位置删除“shapedrawable”:
<com.android.test.shapedrawable.ShapeSquare
android:layout_width="fill_parent"
android:layout_height="wrap_content"
/>
显然,那只是演示的位置。我认为它以某种方式引用了该类。
关于android - 在 XML 中塑造可绘制 View ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6067232/