活动类代码:
conversationList = (ListView)findViewById(android.R.id.list);
ConversationArrayAdapter conversationArrayAdapter=new ConversationArrayAdapter(this, R.layout.conversation_list_item_format_left, conversationDetails);
conversationList.setAdapter(conversationArrayAdapter);
conversationList.setOnItemClickListener(new AdapterView.OnItemClickListener(){
@Override
public void onItemClick(AdapterView<?> arg0, View arg1, int position, long arg3) {
Log.d("test","clicked");
}
});
Adapter类中的getView函数:
if (v == null) {
LayoutInflater vi = (LayoutInflater)ctx.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
if(leftSideMessageNumber.equals(m.getTo())) {
v = vi.inflate(R.layout.conversation_list_item_format_left, null);
} else {
v = vi.inflate(R.layout.conversation_list_item_format_right, null);
}
}
在膨胀时使用两个xml会有问题吗?
我刚从这里找到了一个解决方案,不过是通过深度点击。
如果列表的任何行项包含可聚焦或可点击的视图,那么OnItemClickListener将不起作用。
行项必须具有类似的参数
android:descendantFocusability = "blocksDescendants"。
在这里您可以看到列表项应该是什么样的示例。
你的列表项xml应该是…
row_item.xml (your_xml_file.xml)
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:baselineAligned="false"
android:descendantFocusability="blocksDescendants"
android:gravity="center_vertical" >
// your other widgets here
</LinearLayout>
对我有用的是将下面的代码添加到我的row.xml文件布局中的每个子视图中:
android:focusable="false"
android:focusableInTouchMode="false"
在我的例子中:
<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
android:focusable="false"
android:focusableInTouchMode="false"
android:id="@+id/testingId"
android:text="Name"
//other stuff
/>
<TextView
android:focusable="false"
android:focusableInTouchMode="false"
android:id="@+id/dummyId"
android:text="icon"
//other stuff
/>
<TextView
android:focusable="false"
android:focusableInTouchMode="false"
android:id="@+id/assignmentColor"
//other stuff
/>
<TextView
android:focusable="false"
android:focusableInTouchMode="false"
android:id="@+id/testID"
//other stuff
/>
<TextView
android:focusable="false"
android:focusableInTouchMode="false"
android:text="TextView"
//other stuff
/>
</android.support.constraint.ConstraintLayout>
这是我在Fragment子类中的setOnItemClickListener调用:
CustomListView = (PullToRefreshListCustomView) layout.findViewById(getListResourceID());
CustomListView.setAdapter(customAdapter);
CustomListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Log.d("Testing", "onitem click working");
// other code
}
});
我从这里得到了答案!