I have an Apple
class with two fields, colour
and rotation
, and an AppleView
View which draws the apple in that colour and rotation in its onDraw
method (this is a simplification of my actual code). The AppleView has a default apple (let's say, red and rotated by 0 degrees) which can be reassigned. Here is some pseudocode for the two classes:
public class Apple {
int colour;
int rotation;
}
public class AppleView extends View {
Apple apple = getDefaultApple();
@Override
protected void onDraw(Canvas canvas) {
drawApple(canvas, apple);
}
}
I'd like to make a ListView of AppleViews from an ArrayList of apples. I create two layouts: a 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>
and a list item, which is just an 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>
Finally, I extend ListActivity
and use a custom adapter class to draw the list items:
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;
}
}
}
Although all the right methods are being called (i.e. getView and onDraw for each apple), the ListView does not display:
Where is the error in the above code?