在自定义ListView中的项目上添加onitemClickListener,例如(TextViews,Images,Buttons)

时间:2013-07-02 09:22:31

标签: android listview

我们可以在自定义ListView中的项目上添加onitemClickLIstener,例如(TextViews,Images,Buttons)吗? 如是?然后我们将编写监听器代码

3 个答案:

答案 0 :(得分:4)

确定..你可以通过两种方式添加它

1)。通过在xml文件中定义函数并在自定义适配器类的getview或bindview中定义这些函数。

2)。或者通过在自定义适配器类的bindview或getview中定义onclick侦听器。

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

    if (view == null) {
        Button btn = (Button) view.findViewById(R.id.btn);
        btn.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                // TODO Auto-generated method stub

            }
        });
    }

    return view;

}

答案 1 :(得分:1)

您可以在自定义ListView中定义的项目上添加onClickListeners。请参阅以下代码

holder.txtIncident.setOnClickListener

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

        final ViewHolder holder;
        if (convertView == null) {
            convertView = l_Inflater.inflate(R.layout.headline_item, null);
            holder = new ViewHolder();

            holder.txtIncident = (TextView) convertView
                    .findViewById(R.id.txtIncident);

            convertView.setTag(holder);
        } else {
            holder = (ViewHolder) convertView.getTag();
        }

        holder.txtIncident.setText(String.valueOf(itemList.get(position)
                .getIncident()));

        holder.txtIncident.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                // TODO Auto-generated method stub

            }
        });
        return convertView;
    }

答案 2 :(得分:0)

是的,您可以为每个列表项中的组件创建侦听器。您可以通过创建自定义列表适配器并在其getView方法中设置侦听器来完成此操作。

    public class MyAdapter extends ArrayAdapter<String> {

        private int resourceId;
        private String[] objects;

        public MyAdapter(Context context,  int resourceId, String[] objects) {
           super(context, resourceId,objects);
           this.resourceId = resourceId;
           this.objects = objects;
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            if (convertView == null) {
                LayoutInflater inflater = (LayoutInflater) getSystemService(LAYOUT_INFLATER_SERVICE);
                convertView = inflater.inflate(resourceId, null);
            }

            //Make sure that you use convertView.findViewById and not just findViewById!
            TextView textView1 = convertView.findViewById(R.id.yourTextViewsId);
            textView1.setText(objects[position]);
            textView1.setOnClickListener(new View.OnClickListener(){

                @Override
                public void onClick(View view) {
                    //do something here
                }
            });

            return convertView;
        }
    }