onDraw()未在自定义视图

时间:2016-05-12 16:17:41

标签: android android-layout listview

我已经在Stackoverflow上搜索了一个合适的答案,但找不到任何可以帮助我的东西。

我有一个包含ListView的Fragment。此ListView应显示自定义视图的数组。 问题是,不会调用自定义视图的onDraw()方法。它们被初始化但未绘制。即使强迫他们通过invalidate()绘制也不会改变任何东西。 我已经尝试过设置

this.setWillNotDraw(true);

在构造函数中,没有帮助。 任何帮助将不胜感激。

片段

public static class CustomFragment extends Fragment {

        private ListView list;

        @Override
        public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
            final View rootView = inflater.inflate(R.layout.fragment, container, false);
            list = (ListView)rootView.findViewById(R.id.fragment_list);
            list.setAdapter(new CustomAdapter(getActivity(), R.layout.list_item, somevalues));
            return rootView;
        }
    }

自定义视图

    public class CustomView extends View {

    public static final String TAG = "CustomView";

    public CustomView(Context context) {
        super(context);
        init();
    }

    public CustomView(Context context, AttributeSet attrs) {
        super(context, attrs);
        init();
    }

    public CustomView(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        init();
    }

    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        Log.d(TAG, "Measuring and storing dimensions");
    }

    public void init() {
        Log.d(TAG, "Initializing CustomView");
        this.setWillNotDraw(false);
        invalidate();
    }

    @Override
    protected void onDraw(Canvas canvas) {
        super.onDraw(canvas);
        Log.d(TAG, "OnDraw called");
    }
}

自定义适配器

public static class CustomAdapter extends ArrayAdapter<String> {
        private String[] values;
        private Context context;
        private int resource;

        public CustomAdapter(Context context, int resource, String[] values) {
            super(context, resource, values);
            this.values = values;
            this.context = context;
            this.resource = resource;
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            LayoutInflater inflater = (LayoutInflater)context.getSystemService(LAYOUT_INFLATER_SERVICE);
            View rowView = inflater.inflate(resource, parent, false);
            CustomView cView = (CustomView)rowView.findViewById(R.id.cview);
            cView.setColors(values);
            return rowView;
        }
    }

1 个答案:

答案 0 :(得分:0)

您应该在init方法中设置setWillNotDraw(false)。