我的ListView
显示没有extends ListActivity
。我想启用setOnItemClickListener
。这是onCreate
adapter = new CustomAdapter(this, MyDB);
setListAdapter(adapter);
mListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View view, int position,
long id) {
Toast.makeText(getBaseContext(), "test", Toast.LENGTH_LONG).show();
}
我使用以下代码启用ListView
。
protected ListView getListView() {
if (mListView == null) {
mListView = (ListView) findViewById(android.R.id.list);
empty = (TextView) findViewById(android.R.id.empty);
mListView.setEmptyView(empty);
}
return mListView;
}
protected void setListAdapter(ListAdapter adapter) {
getListView().setAdapter(adapter);
}
但是,setOnItemClickListener
无效。
答案 0 :(得分:2)
如果您在里面使用可点击按钮,我认为,最好的方法是不使用AdapterView.OnItemClickListener
,而是使用通常的onClick
事件。
或者使用android:descendantFocusability="blocksDescendants"
我希望你的情况。
答案 1 :(得分:0)
也许你在xml布局中设置onClickListener - 删除它。
您可以为没有onClickListener
ListView.setOnItemClickListener
答案 2 :(得分:0)
您可以在适配器上设置OnClickListener,如下所示 -
public class DeviceList_Adapter extends BaseAdapter implements View.OnClickListener
{
/************* CustomAdapter Constructor *****************/
public DeviceList_Adapter(Activity a, ArrayList d)
{
/********** Take passed values **********/
activity = a;
data=d;
/*********** Layout inflator to call external xml layout () ***********/
inflater = (LayoutInflater)activity.
getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
public int getCount() {
if(data.size()<=0)
return 1;
return data.size();
}
public Object getItem(int position) {
return position;
}
public long getItemId(int position) {
return position;
}
public View getView(int position, View convertView, ViewGroup parent)
{
View vi = convertView;
ViewHolder holder;
if(convertView==null){
/****** Inflate listitem_device.xml file for each row ( Defined below ) *******/
vi = inflater.inflate(R.layout.listitem_device, null);
/******** Set Item Click Listner for LayoutInflater for each row *******/
vi.setOnClickListener(new OnItemClickListener(position));
}
return vi;
}
@Override
public void onClick(View v) {
Log.v("CustomAdapter", "=====Row button clicked=====");
}
/********* Called when Item click in ListView ************/
private class OnItemClickListener implements View.OnClickListener {
private int mPosition;
OnItemClickListener(int position){
mPosition = position;
}
@Override
public void onClick(View arg0)
{
MainActivity mainActivity = (MainActivity)activity;
/**** Call onItemClick Method inside CustomListViewAndroidExample Class ( See Below )****/
mainActivity.onItemClick(mPosition);
}
}
}
在您计划使用listview的活动中有一个名为onItemClick()的方法。每次在列表视图上单击一行时,都会调用此方法。