如何派生BaseAdapter并在没有XML的情况下自定义视图?

时间:2013-05-08 05:06:51

标签: android

我不想为视图引用资源(也就是XML布局),甚至不想使用inflater服务。

我已经看过许多用于列表视图示例的页面,但是每个人似乎最多都是从ArrayAdapter或CursorAdapter派生他们的类。

那么,有没有人可以向我展示一个如何从BaseAdapter派生类并通过修改其'getView'方法在其中制作自定义列表视图的示例?

1 个答案:

答案 0 :(得分:1)

您可以在Java中以编程方式创建视图并设置其属性。如果您熟悉它,它几乎与使用AWT / Swing相同。

public class MyAdapter extends BaseAdapter {
    private List<String> items; // could be an array/other structure 
                                // using Strings as example

    public MyAdapter(Context context, List<String> items) {
        this.context = context;
        this.items = new ArrayList<String>(items);
    }

    public int getCount() {
        return items.size();
    }

    // notice I changed the return type from Object to String
    public String getItem(int position) {
        return items.get(position);
    }

    public View getView(int position, View convertView, ViewGroup parent) {
        // Really dumb implementation, you should use the convertView arg if it isn't null
        TextView textView = new TextView(context);
        textView.setText(getItem(position);
        /* call other setters on TextView */

        return textView;
    }
}

您可能必须覆盖其他一些方法,但它们应该是不言自明的。