在Android中,要在ListView中使用OnTouchListener,您需要為ListView的每個子項設置一個OnItemClickListener,然后在子項的布局中添加一個OnTouchListener。這是一個簡單的示例:
<ListView
android:id="@+id/list_view"
android:layout_width="match_parent"
android:layout_height="wrap_content"/>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal"
android:padding="8dp">
<TextView
android:id="@+id/text_view"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1" />
<ImageView
android:id="@+id/image_view"
android:layout_width="48dp"
android:layout_height="48dp"
android:src="@drawable/ic_launcher_background" />
</LinearLayout>
public class CustomAdapter extends BaseAdapter {
private Context context;
private List<String> dataList;
public CustomAdapter(Context context, List<String> dataList) {
this.context = context;
this.dataList = dataList;
}
@Override
public int getCount() {
return dataList.size();
}
@Override
public Object getItem(int position) {
return dataList.get(position);
}
@Override
public long getItemId(int position) {
return position;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder viewHolder;
if (convertView == null) {
convertView = LayoutInflater.from(context).inflate(R.layout.list_item, parent, false);
viewHolder = new ViewHolder();
viewHolder.textView = convertView.findViewById(R.id.text_view);
viewHolder.imageView = convertView.findViewById(R.id.image_view);
convertView.setTag(viewHolder);
} else {
viewHolder = (ViewHolder) convertView.getTag();
}
viewHolder.textView.setText(dataList.get(position));
return convertView;
}
static class ViewHolder {
TextView textView;
ImageView imageView;
}
}
ListView listView = findViewById(R.id.list_view);
List<String> dataList = new ArrayList<>();
// 添加數據到dataList
CustomAdapter adapter = new CustomAdapter(this, dataList);
listView.setAdapter(adapter);
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
// 處理item點擊事件
}
});
listView.setOnTouchListener(new View.OnTouchListener() {
@Override
public boolean onTouch(View v, MotionEvent event) {
// 處理觸摸事件
return false;
}
});
現在,您已經成功地為ListView中的每個子項設置了OnTouchListener。您可以在onTouch
方法中處理觸摸事件。