有关这方面的文档非常令人困惑。我只需将矩形添加到我在main.xml布局文件中定义的视图中。这将是布局的一小部分。
我想要实现的是,我想增加一个房间的货架,但由于房间的形状和货架的变化,我需要增加他们的程序。
下面是我的main.xml文件的一小部分,您可以看到我定义的视图:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
android:id="@+id/relativeLayout2"
android:layout_width="600dp"
android:layout_height="650dp"
android:layout_marginTop="70dp"
android:layout_marginLeft="30dp"
android:layout_toRightOf="@+id/relativeLayout1" >
<TextView
android:id="@+id/textView3"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:text="@string/getDirections"
android:textSize="20dp"
android:textStyle="bold" />
<View
android:id="@+id/roomplan"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_below="@+id/textView3"
android:layout_marginTop="40dp"
android:background="@android:color/white" />
</RelativeLayout>这是我为处理动态更改而创建的自定义视图类:
public class CustomView extends View {
ShapeDrawable roomFrame;
ArrayList<ShapeDrawable> shelfFrames;
public CustomView(Context context) {
super(context);
// TODO Auto-generated constructor stub
}
@Override
protected void onDraw(Canvas canvas){
super.onDraw(canvas);
roomFrame.draw(canvas);
for (ShapeDrawable shelfFrame : shelfFrames){
shelfFrame.draw(canvas);
}
}
public void setRoom(Stage stage){
roomFrame = new ShapeDrawable(new RectShape());
roomFrame.getPaint().setColor(0xff74AC23);
roomFrame.setBounds(10, 10, stage.getWidth(), stage.getHeight());
}
public void setShelves(ArrayList<Shelf> shelves){
shelfFrames = new ArrayList<ShapeDrawable>();
for(int i = 0; i<shelves.size(); i++){
ShapeDrawable shelfFrame = new ShapeDrawable(new RectShape());
shelfFrame.getPaint().setColor(0xff74AC23);
shelfFrame.setBounds(shelves.get(i).getXPosition(), shelves.get(i).getYPosition(), shelves.get(i).getWidth(), shelves.get(i).getHeight());
shelfFrames.add(shelfFrame);
}
}
}现在,简单地说,当询问一个新的房间计划时,我试图将这个类分配给xml布局中的View对象:
public void loadRoomPlan(Room room, ArrayList<Shelf> shelves){
CustomView asdsView = (CustomView)findViewById(R.id.roomplan);
asdsView.setRoom(room);
asdsView.setShelves(shelves);
asdsView.invalidate();
}我总能得到
引起的: java.lang.ClassCastException: android.view.View不能转换为org.example.myproject.CustomView
错误。
也许我做的很不对,不是吗?
发布于 2012-06-02 23:06:37
错误似乎出现在这一行:
CustomView asdsView = (CustomView)findViewById(R.id.shopplan);shopplan是什么?如果这是一个错误,并且您的意思是R.id.roomplan试图在您的自定义视图的布局中替换视图:
<org.example.myproject.CustomView
android:id="@+id/roomplan"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_below="@+id/textView3"
android:layout_marginTop="40dp"
android:background="@android:color/white" />更新:
尝试将另外两个构造函数添加到CustomView类中:
public CustomView(Context context, AttributeSet attrs) {
super(context, attrs);
}
public CustomView(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
}在xml布局中使用自定义视图时,视图必须处理布局属性(构造函数AttributeSet param)。
https://stackoverflow.com/questions/10866551
复制相似问题