我有一个Apple
有两个字段的类,colour
和rotation
,以及一个AppleView
View ,它以该颜色绘制苹果并在其onDraw
方法中旋转(这是我实际代码的简化)。AppleView 有一个可以重新分配的默认苹果(比如说,红色并旋转 0 度)。这是这两个类的一些伪代码:
public class Apple {
int colour;
int rotation;
}
public class AppleView extends View {
Apple apple = getDefaultApple();
@Override
protected void onDraw(Canvas canvas) {
drawApple(canvas, apple);
}
}
我想从苹果的 ArrayList 中制作 AppleViews 的 ListView。我创建了两个布局:一个 ListView ( R.layout.list_view
):
<?xml version="1.0" encoding="utf-8"?>
<ListView xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="@android:id/list">
</ListView>
和一个列表项,它只是一个AppleView
( R.layout.list_item
):
<?xml version="1.0" encoding="utf-8"?>
<com.mypackage.AppleView xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="@+id/apple">
</com.mypackage.AppleView>
最后,我扩展ListActivity
并使用自定义适配器类来绘制列表项:
public class MyListActivity extends ListActivity {
ArrayList<Apple> apples = new ArrayList<Apple>();
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.list_view);
// Add 100 random apples to the list for demonstration.
for (int i = 0; i < 100; i++) {
apples.add(getRandomApple());
}
getListView().setAdapter(new MyAdapter(this, R.layout.list_item, apples));
}
class MyAdapter extends ArrayAdapter<Apple> {
public MyAdapter(Context context, int resourceID, ArrayList<Apple> items) {
super(context, resourceID, items);
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
if (convertView == null) {
convertView = getLayoutInflater().inflate(R.layout.list_item, parent, false);
}
// Change this AppleView's apple to the new ArrayList element at this position.
AppleView appleView = (AppleView) convertView.findViewById(R.id.apple);
appleView.apple = apples.get(position);
return convertView;
}
}
}
尽管调用了所有正确的方法(即每个苹果的 getView 和 onDraw),但 ListView 不显示:
上面代码的错误在哪里?