带有按钮/清单的Android Listview

时间:2014-10-05 20:15:38

标签: android listview button

我是Android上ListViews的新手。

我需要一个4x5的布局(按钮,清单和文本框),我正在考虑使用ListViews,每个布局有一行(4个按钮,4个清单和4个文本框),然后制作5个项目。

如果我只做一行(没有ListView),我就设法让它发挥作用。

但是当我搞乱ListViews时,我不知道如何在按钮和清单上使用“onClick”,所以我知道按钮被按下了什么线......

有人可以为我指出一个示例或代码吗?

由于

1 个答案:

答案 0 :(得分:1)

该职位将自动管理。如果您的活动延伸ListActivityListFragment,则只需覆盖onListItemClick

@Override  
    protected void onListItemClick(ListView l, View v, int pos, long id) {  
        super.onListItemClick(l, v, pos, id);
        // your action 
}

同样,如果您的Activity不扩展ListActivityListFragment,则必须在ListView上设置监听器:

listView.setOnItemClickListener(new OnItemClickListener() {

            @Override
            public void onItemClick(AdapterView<?> parent, View view,
                    int position, long id) {
                // TODO Auto-generated method stub

            }
        });

当然,此事件与列表中的整个项目有关。相反,如果您想为列表项中的每个视图设置一个侦听器,则应该在适配器中执行此操作。假设使用ArrayAdapter

public class CustomAdapter extends ArrayAdapter<MyObject> {
        private final Context context;        
        private ArrayList<MyObject> list;

        public CustomAdapter(Context context, ArrayList<MyObject> list)
        {
            super(context, R.layout.adapter_row_path, list);
            this.context = context;     
            this.list = list;  
        }

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

            View rowView = convertView;
            PathHolder holder;  

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

            holder = new ViewHolder();
            holder.b1 = (Button) rowView.findViewById(R.id.b1);
            holder.b2 = (Button) rowView.findViewById(R.id.b2);

            rowView.setTag(holder);

            }else {
                holder = (ViewHolder) rowView.getTag();
            }

            setRow(holder, position);
            return rowView;
            }

          private void setRow(Holder holder, position){
              holder.b1.setOnClickListener(new OnClickListener() {

                @Override
                public void onClick(View v) {
                    // action on button 1 (you know also position here)
                }
            });

            holder.b2.setOnClickListener(new OnClickListener() {

                @Override
                public void onClick(View v) {
                    // action on button 2 (you know also position here)
                }
            });
          }

    }


    static class ViewHolder {
        Button b1;
        Button b2;     
    }