自定义控件,继承自 ListView

public class MyListView extends ListView {

    /**
     * 如果在xml中创建并设置了style,就会调用三个参数的。
     *
     * @param context
     * @param attrs
     * @param defStyle
     */
    public MyListView(Context context, AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);
    }

    /**
     * 如果是在xml中创建这个控件并且没有指定style,会调用两个参数的
     *
     * @param context
     * @param attrs
     */
    public MyListView(Context context, AttributeSet attrs) {
        super(context, attrs);
        String[] ss = {"abc", "123", "qwert", "asdf"};
        ArrayAdapter<String> aa = new ArrayAdapter<String>(getContext(), android.R.layout.simple_list_item_1, ss);
        setAdapter(aa);
    }

    /**
     * 在java代码中直接new一个自定义的 ListView,会调用一个参数的构造函数
     */
    public MyListView(Context context) {
        super(context);
    }
}

  

布局文件:

    <com.test.testlistview.MyListView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:id="@+id/myListView"
        android:layout_alignParentTop="true"
        android:layout_alignParentLeft="true"
        android:layout_alignParentStart="true"/>
原文地址:https://www.cnblogs.com/jarod99/p/7419925.html