ListView不显示自定义适配器类

时间:2013-09-14 18:17:18

标签: android listview android-listview android-arrayadapter

我有一个Apple课程,其中包含两个字段colourrotation,以及一个AppleView视图,用于在其{{1}中以该颜色和旋转绘制苹果方法(这是我实际代码的简化)。 AppleView有一个默认的苹果(比方说,红色并旋转0度)可以重新分配。这是两个类的一些伪代码:

onDraw

我想从Apple的ArrayList创建一个AppleViews的ListView。我创建了两个布局:ListView(public class Apple { int colour; int rotation; } public class AppleView extends View { Apple apple = getDefaultApple(); @Override protected void onDraw(Canvas canvas) { drawApple(canvas, apple); } } ):

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

虽然调用了所有正确的方法(即每个苹果的getView和onDraw),但ListView不会显示:

enter image description here

上述代码中的错误在哪里?

2 个答案:

答案 0 :(得分:0)

未定义设置为match_parent的ListView元素的高度(即它为0),因为高度由内容的大小决定。要解决此问题,请为元素指定固定高度,例如:

<?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="100dp" /* THIS LINE CHANGED */
      android:id="@+id/apple">
</com.mypackage.AppleView>

答案 1 :(得分:0)

I have made some change with your arrayadapter.
 class MyAdapter extends ArrayAdapter<ArrayList<Apple>> {
        private ArrayList<Apple> apple = null;
        public MyAdapter(Context context, int resourceID, ArrayList<Apple> items) {
            super(context, resourceID, items);
            this.apple = items;
        }


  @Override
        public int getCount() {
    //Check with this size if it is greater than zero,then list is visible
            return apple.size();
        }


        @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 = apple.get(position);

            return convertView;
        }
    }