我们可以在 android 的 ListView 中同时拥有 Button 和 onItemClick 侦听器吗? [英] can we have both of Button and onItemClick listener in ListView in android?
问题描述
我在 ListView
和 onClickListener
的每一行中有 Button
用于 Button
.我也想将 onItemSelectListener
添加到我的 ListView
中.是否可以?如果是,我该怎么做?
任何帮助将不胜感激.
I have Button
in each row of ListView
and onClickListener
for Button
. I want to add onItemSelectListener
to my ListView
too. Is it possible? If yes how can I do that?
Any help will be appreciated.
推荐答案
是的,有可能...
在为列表视图创建自定义视图适配器时,您必须在按钮上添加 onclicklistener并且您还可能需要在 Listview 上添加 onItemSelectListener.它会起作用.
While creating custom view adapter for listview, u have to add onclicklistener on button and u can also need to add onItemSelectListener on Listview. It would work.
使用列表视图代码作为
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;
}
}
现在使用下面的代码处理列表项内的点击
Now to handle click inside a list item use the below code
android:focusable="false"
android:focusableInTouchMode="false"
在创建 Button 标签时设置这些行
set these lines while creating Button tag
它会起作用...请让我知道您的反馈..
It would work ... Please let me know your feedback..
这篇关于我们可以在 android 的 ListView 中同时拥有 Button 和 onItemClick 侦听器吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!