Android在ListView的onTouch事件中獲取選中項的值
在Android開發中經常使用ListView,最近使用ListView製作一個仿QQ的滑動刪除控制元件時遇到一個問題,就是使用ListView的onTouch事件無法獲取選中項的值,講過一番思考和在網上看的一些資料,想到一個解決辦法。
ListView listView = (ListView) findViewById(R.id.listView1);
listView.setOnTouchListener(new OnTouchListener() {
@Override
public boolean onTouch(View v, MotionEvent event) {
// TODO 自動生成的方法存根
int position = ((ListView)v).pointToPosition((int)event.getX(), (int)event.getY());
System.out.println(position);
return false;
}
});
使用函式pointToPosition,引數是觸控ListView的橫縱座標。pointToPosition的詳情可檢視原始碼。
/**
* Maps a point to a position in the list.
*
* @param x X in local coordinate
* @param y Y in local coordinate
* @return The position of the item which contains the specified point, or
* {@link #INVALID_POSITION} if the point does not intersect an item.
*/
public int pointToPosition(int x, int y) {
Rect frame = mTouchFrame;
if (frame == null) {
mTouchFrame = new Rect();
frame = mTouchFrame;
}
final int count = getChildCount();
for (int i = count - 1; i >= 0; i--) {
final View child = getChildAt(i);
if (child.getVisibility() == View.VISIBLE) {
child.getHitRect(frame);
if (frame.contains(x, y)) {
return mFirstPosition + i;
}
}
}
return INVALID_POSITION;
}
相關文章
- android開發中如何動態獲取listview中的item的值AndroidView
- 在js中獲取 input checkbox裡選中的多個值JS
- Android自定義OnTouch事件Android事件
- android中的ListViewAndroidView
- XamarinEssentials教程獲取首選項的值
- 使用layui框架的select獲取選中的值UI框架
- JavaScript 獲取選中checkbox核取方塊的值JavaScript
- jQuery 利用萬用字元獲取多選框選中的值jQuery字元
- Android ListView 進階——從列表中獲取值AndroidView
- JavaScript獲取選中radio單選按鈕值JavaScript
- 【Javascript】獲取選中的文字JavaScript
- gitlab cicd中獲取tag值的方式Gitlab
- 在Java中獲取Android端登陸的裝置資訊JavaAndroid
- JavaScript獲取選中checkbox核取方塊的選中值JavaScript
- js中獲取鍵盤事件JS事件
- 【我的Android進階之旅】解決重寫onTouch事件提示的警告:onTouch should call View#performClick when a click is detectedAndroid事件ViewORM
- PHP中如何獲取下拉選單的值PHP
- 【Azure Developer】使用 CURL 獲取 Key Vault 中 Secrets 中的值Developer
- python中獲取如何Series值Python
- 選項中選擇現在
- 在 Fedora 中獲取最新的 Ansible 2.8
- Android中點選事件的四種寫法詳解Android事件
- Spring Boot EL獲取配置檔案中的值的方式Spring Boot
- JavaScript獲取選中checkbox valueJavaScript
- 獲取ChoiceGroup多選狀態下的值
- JavaScript獲取滑鼠在元素中的座標JavaScript
- JavaScript獲取元素在陣列中的位置JavaScript陣列
- 透過滑鼠事件獲取滑鼠位置在3d中的座標mouse/Raycaster事件3DAST
- 直播商城原始碼,PopupWindow選單在ListView中顯示原始碼View
- JQuery 獲取select被選中的value和textjQuery
- jquery獲取下拉框選中的屬性值jQuery
- 在 JDBC 中獲取插入 IDJDBC
- Flutter 中 ListView 的使用FlutterView
- jQuery獲取點選td單元格的值jQuery
- 在Linux中,ls命令有哪些常用的選項?Linux
- 在Linux中,如何獲取CPU的總核心數?Linux
- 確保從列表中獲取可用值
- Android ListView中複雜資料流的高效渲染(一)AndroidView
- jquery和bootstrap獲取checkbox選中的多行資料jQueryboot