我有一个带有自定义适配器的listview,我需要访问这个listview的各个行的视图。我正在尝试使用getChildat()执行此操作,但它返回的是空值。
这是我的列表视图:

myListView = (ListView) findViewById (R.id.listViewLayout);

这是自定义适配器:
    public class MyListAdapter extends BaseAdapter {
       ...
        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            if (convertView == null) {
                LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
                convertView = inflater.inflate(R.layout.list_row_layout, parent, false);
            }
            ...
    }

我创建一个列表,并为listview设置它:
List <String> myList = new ArrayList<String>();
myList.add("entry 1");
myList.add("entry 2");
myList.add("entry 3");
MyListAdapter myListAdapter = new MyListAdapter(getApplicationContext(), myList);
myListView.setAdapter(myListAdapter);

现在,我想访问单个行的视图。
View v = myListView.getChildAt(myListView.getFirstVisiblePosition());

不管怎样,这个v都是空的。此外,myListView.getChildCount()始终返回空值。
我错过了什么?是否需要将convertView添加到parent中的getView()?我是否向inflate传递了错误的参数?
我费了很大的劲才弄明白。请帮帮我!
编辑:我正在发布MyListAdapter类:
public class MyListAdapter extends BaseAdapter {

    private Context context;
    private List<String> myList;

    public MyListAdapter(Context c, List<String> m) {
        context = c;
        myList = m;
    }

    @Override
    public int getCount() {
        return myList.size();
    }

    @Override
    public Object getItem(int position) {
        return myList.get(position);
    }

    @Override
    public long getItemId(int position) {
        return position;
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {

        final int pos = position;

        if (convertView == null) {
            LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
            convertView = inflater.inflate(R.layout.list_row_layout, parent, false);
        }

            TextView text = (TextView) convertView.findViewById(R.id.itemText);
            text.setText(myList.get(pos));

            // Set the onClick Listener on this button
            Button rowButton = (Button) convertView.findViewById(R.id.itemButton);

            //commenting next two lines makes the list row clickable
            rowButton.setFocusableInTouchMode(false);
            rowButton.setFocusable(false);

            rowButton.setOnClickListener(new View.OnClickListener() {
                public void onClick(View v) {
                    Toast.makeText(context, myList.get(pos), Toast.LENGTH_SHORT).show();
                }
            });
            convertView.setTag(pos);
            return convertView;
    }
}

最佳答案

很可能你在onCreate()中做了所有这些。任何与视图相关的方法都将返回null(或空),因为列表尚未呈现。你需要孩子的视角做什么?

08-25 14:25
查看更多