我们可以在Android的ListView中同时拥有Button和onItemClick监听器吗?

时间:2014-05-13 04:53:05

标签: android android-listview onclicklistener onitemselectedlistener

ButtonListView的每一行都有onClickListener Button。我也希望将onItemSelectListener添加到ListView。可能吗?如果是,我该怎么做? 任何帮助将不胜感激。

2 个答案:

答案 0 :(得分:3)

是的,有可能......

在为listview创建自定义视图适配器时,您必须在按钮上添加onclicklistener 你还需要在Listview上添加onItemSelectListener。 它会起作用。

将listview代码用作

listView = (ListView) findViewById(R.id.listView2);
      listView .setAdapter(new CustomListAdapter (this,userIDArr));


      listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
          @Override
          public void onItemClick(AdapterView<?> arg0, View arg1, int position, long arg3) {

              Toast.makeText(Activity.this,
                        "Item in position " + position + " clicked", Toast.LENGTH_LONG).show();
          }
        });

并创建像

这样的适配器
public class CustomListAdapter extends ArrayAdapter<String>
{
    Activity context;
    public CustomListAdapter (Activity context, ArrayList<String> names) {
        super(context, R.layout.list_item, names);
        this.context = context;
    }
    private class ViewHolder {

        public TextView Description;
        public Button  UploadBtn;
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        ViewHolder holder;
        View rowView = convertView;
        if (rowView == null) {
            LayoutInflater inflater = context.getLayoutInflater();
            rowView = inflater.inflate(R.layout.list_item, null, true);
            holder = new ViewHolder();

            holder.Description = (TextView) rowView.findViewById(R.id.User_status);
            holder.UploadBtn = (Button) rowView.findViewById(R.id.uploadbutton);
            holder.UploadBtn.setOnClickListener(new View.OnClickListener() {  

                    public void onClick(View v) {  
                    Toast.makeText(Activity.this," Button clicked",Toast.LENGTH_SHORT).show();
                    }   
                }); 
                rowView.setTag(holder);
        } else {
            holder = (ViewHolder) rowView.getTag();
        }

        holder.Description.setText("U r in middle");
        return rowView;
    }
}

现在要处理列表项内的单击,请使用以下代码

android:focusable="false"
android:focusableInTouchMode="false"

在创建Button标记

时设置这些行

它会起作用...... 请让我知道您的反馈意见..

答案 1 :(得分:0)

雅可能!!!

你可以在android中使用自定义视图或在android中自定义列表视图