Android ListView长按事件弹出菜单并获取选中的item

Stella981
• 阅读 921

看了很多listview的长按事件,但几乎都是只给出弹出菜单的代码,没有给出选中的某个项的代码,我贴个全的吧,免得摸索麻烦

思路就是

listview在父窗口先注册一个长按弹出菜单registerReceiver=》设置一个长按的listener,保存好选中item数据=》onCreateContextMenu添加菜单=》onContextItemSelected菜单响应处理;

就这么简单。

[java] view plain copy print ?

  1. import java.util.ArrayList;

  2. import java.util.Collections;

  3. import java.util.Comparator;

  4. import java.util.HashMap;

  5. import java.util.Map;

  6. import org.json.JSONException;

  7. import org.json.JSONObject;

  8. import android.app.Activity;

  9. import android.app.ProgressDialog;

  10. import android.content.BroadcastReceiver;

  11. import android.content.Context;

  12. import android.content.Intent;

  13. import android.content.IntentFilter;

  14. import android.content.res.Resources;

  15. import android.graphics.Color;

  16. import android.os.Bundle;

  17. import android.text.Spannable;

  18. import android.text.SpannableStringBuilder;

  19. import android.text.style.ForegroundColorSpan;

  20. import android.util.Log;

  21. import android.view.ContextMenu;

  22. import android.view.ContextMenu.ContextMenuInfo;

  23. import android.view.LayoutInflater;

  24. import android.view.MenuItem;

  25. import android.view.View;

  26. import android.view.View.OnClickListener;

  27. import android.view.View.OnCreateContextMenuListener;

  28. import android.view.ViewGroup;

  29. import android.view.Window;

  30. import android.widget.AdapterView;

  31. import android.widget.AdapterView.OnItemClickListener;

  32. import android.widget.AdapterView.OnItemLongClickListener;

  33. import android.widget.BaseAdapter;

  34. import android.widget.Button;

  35. import android.widget.EditText;

  36. import android.widget.LinearLayout;

  37. import android.widget.ListView;

  38. import android.widget.TextView;

  39. import android.widget.Toast;

  40. public class CommentsListActivity extends Activity

  41. {

  42. private String m_jid = "0";

  43. private ListView m_listView;

  44. private EditText m_ETReply;

  45. private Appdata m_appdata;

  46. private TextView m_TVReply;

  47. private TextView m_TVid;

  48. private LinearLayout m_ReplyArea;

  49. private String m_replycCmmentID = "";

  50. private String m_replyCommentContent = "";

  51. private boolean m_bcomments = false;

  52. private ArrayList m_commentList = new ArrayList();

  53. private Helper.SmartJSONArray m_commentObj = null;

  54. public void onCreate(Bundle savedInstanceState)

  55. {

  56. super.onCreate(savedInstanceState);

  57. requestWindowFeature(Window.FEATURE_CUSTOM_TITLE);

  58. setContentView(R.layout.comments);

  59. getWindow().setFeatureInt(Window.FEATURE_CUSTOM_TITLE,

  60. R.layout.title);

  61. m_appdata = (Appdata)this.getApplicationContext();

  62. m_listView = (ListView)this.findViewById(R.id.listViewShow);

  63. m_ETReply = (EditText)this.findViewById(R.id.editTextComment);

  64. m_ReplyArea = (LinearLayout)this.findViewById(R.id.ReplyArea);

  65. m_TVReply = (TextView)m_ReplyArea.findViewById(R.id.TVReply);

  66. m_TVid = (TextView)this.findViewById(R.id.TVid);

  67. Button btnBefore = (Button)this.findViewById(R.id.btn_before);

  68. btnBefore.setText(R.string.back);

  69. btnBefore.setVisibility(View.VISIBLE);

  70. Intent intentFrom = this.getIntent();

  71. Bundle bd = intentFrom.getExtras();

  72. this.m_jid = bd.getString("jid");

  73. TextView viewTitle = (TextView)this.findViewById(R.id.app_title);

  74. viewTitle.setText("\"" + Helper.SmartText(bd.getString("title"), 10, true) + "\"的评论");

  75. IntentFilter intentFilter= new IntentFilter();

  76. intentFilter.addAction(Helper.INTENAL_ACTION_GETPLANCOMMENTS);

  77. registerReceiver(br,intentFilter);

  78. Intent intent= new Intent(Helper.INTENAL_ACTION_GETPLANCOMMENTS);

  79. sendBroadcast(intent);

  80. onLongClickListView();

  81. }

  82. @Override

  83. public void onDestroy()

  84. {

  85. super.onDestroy();

  86. unregisterReceiver(br);

  87. }

  88. class SortByTime implements Comparator {

  89. public int compare(JSONObject o1, JSONObject o2) {

  90. try {

  91. if (Helper.getDiffDays(o1.getString("time"), o2.getString("time")) < 0)

  92. return 1;

  93. } catch (JSONException e) {

  94. e.printStackTrace();

  95. }

  96. return 0;

  97. }

  98. }

  99. public void comment(View v)

  100. {

  101. IntentFilter intentFilter= new IntentFilter();

  102. intentFilter.addAction(Helper.INTENAL_ACTION_GETPLANDOCOMMENT);

  103. registerReceiver(br,intentFilter);

  104. Intent intent= new Intent(Helper.INTENAL_ACTION_GETPLANDOCOMMENT);

  105. sendBroadcast(intent);

  106. }

  107. public void doBefore(View v)

  108. {

  109. CommentsListActivity.this.finish();

  110. }

  111. void onLongClickListView()

  112. {

  113. m_listView.setOnItemLongClickListener(itemLongClick);

  114. registerForContextMenu(m_listView);

  115. }

  116. public void onCreateContextMenu(ContextMenu menu, View v,

  117. ContextMenuInfo menuInfo) {

  118. super.onCreateContextMenu(menu, v, menuInfo);

  119. menu.add(0,0,0,"回复评论");

  120. }

  121. @Override

  122. public boolean onContextItemSelected(MenuItem aItem) {

  123. ContextMenuInfo menuInfo = (ContextMenuInfo) aItem.getMenuInfo();

  124. Toast ta;

  125. ta = Toast.makeText(CommentsListActivity.this, "onContextItemSelected", Toast.LENGTH_LONG);

  126. ta.show();

  127. /* Switch on the ID of the item, to get what the user selected. */

  128. switch (aItem.getItemId()) {

  129. case 0:

  130. if(!CommentsListActivity.this.m_replycCmmentID.equals(""))

  131. {

  132. CommentsListActivity.this.m_ReplyArea.setVisibility(View.VISIBLE);

  133. CommentsListActivity.this.m_TVReply.setText(this.m_replyCommentContent);

  134. CommentsListActivity.this.m_TVid.setText(m_replycCmmentID);

  135. }

  136. return true;

  137. }

  138. return false;

  139. }

  140. void initData()

  141. {

  142. int diarycount = this.m_commentObj.getLength();

  143. if( diarycount >= 1)

  144. {

  145. for (int i = 0; i < diarycount; i++)

  146. {

  147. this.m_commentList.add(this.m_commentObj.getObj(i));

  148. }

  149. Collections.sort(this.m_commentList, new SortByTime());

  150. }

  151. CommentItemAdapter dia = new CommentItemAdapter(this);

  152. m_listView.setAdapter(dia);

  153. }

  154. void addCommentItem(JSONObject objCommentItem)

  155. {

  156. try {

  157. objCommentItem.put("from_nick", objCommentItem.getString("user_name"));

  158. } catch (JSONException e) {

  159. e.printStackTrace();

  160. }

  161. m_ETReply.setText("");

  162. this.m_commentList.add(0, objCommentItem);

  163. CommentItemAdapter adp = (CommentItemAdapter)m_listView.getAdapter();

  164. adp.notifyDataSetChanged();

  165. m_listView.setFocusable(true);

  166. }

  167. public class CommentData

  168. {

  169. public TextView TVname;

  170. public TextView TVtime;

  171. public TextView TVcontent;

  172. public TextView TVcid;

  173. }

  174. public class CommentItemAdapter extends BaseAdapter

  175. {

  176. private LayoutInflater mInflater;

  177. public CommentItemAdapter(Context context)

  178. {

  179. this.mInflater = LayoutInflater.from(context);

  180. }

  181. public View getConvertView(int i)

  182. {

  183. View view = mInflater.inflate(getItemViewType(i), null);

  184. CommentData item = new CommentData();

  185. item.TVname = (TextView)view.findViewById(R.id.TVname);

  186. item.TVtime = (TextView)view.findViewById(R.id.TVtime);

  187. item.TVcontent = (TextView)view.findViewById(R.id.TVcontent);

  188. item.TVcid = (TextView)view.findViewById(R.id.TVcid);

  189. view.setTag(item);

  190. return view;

  191. }

  192. @Override

  193. public int getCount() {

  194. return CommentsListActivity.this.m_commentList.size();

  195. }

  196. @Override

  197. public int getItemViewType(int position) {

  198. return R.layout.listview_item_comment;

  199. }

  200. @Override

  201. public Map<String,Object> getItem(int arg0) {

  202. return null;

  203. }

  204. @Override

  205. public long getItemId(int arg0) {

  206. return arg0;

  207. }

  208. @Override

  209. public View getView(int position, View convertView, ViewGroup parent) {

  210. View view = null;

  211. if(convertView == null)

  212. {

  213. view = getConvertView(position);

  214. }

  215. else

  216. {

  217. view = convertView;

  218. }

  219. CommentData item = (CommentData)view.getTag();

  220. try {

  221. JSONObject obj = CommentsListActivity.this.m_commentList.get(position);

  222. String strTime = obj.getString("time");

  223. item.TVtime.setText(strTime);

  224. item.TVcontent.setText(Helper.outToTextArea(obj.getString("content")));

  225. String str = obj.getString("from_nick");

  226. item.TVname.setText(str);

  227. item.TVcid.setText(obj.getString("id"));

  228. } catch (JSONException e) {

  229. e.printStackTrace();

  230. }

  231. return view;

  232. }

  233. }

  234. private BroadcastReceiver br = new BroadcastReceiver() {

  235. @Override

  236. public void onReceive(Context context, Intent intent) {

  237. String action = intent.getAction();

  238. m_bcomments = action.equals(Helper.INTENAL_ACTION_GETPLANCOMMENTS);

  239. boolean cdocomment = action.equals(Helper.INTENAL_ACTION_GETPLANDOCOMMENT);

  240. if( m_bcomments || cdocomment){

  241. final ProgressDialog progressDialog = ProgressDialog.show(CommentsListActivity.this, null, "亲,稍等片刻哦...", true, false);

  242. progressDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);

  243. HttpUtilService loginService = new HttpUtilService(CommentsListActivity.this.m_appdata.getToken());

  244. Map<String, String> params = new HashMap<String, String>() ;

  245. if(m_bcomments)

  246. {

  247. params.put("jid", CommentsListActivity.this.m_jid);

  248. params.put("page", "1");

  249. }

  250. else

  251. {

  252. params.put("id", CommentsListActivity.this.m_jid);

  253. params.put("title", "null");

  254. if(CommentsListActivity.this.m_ReplyArea.getVisibility() == View.VISIBLE)

  255. {

  256. String strReply = m_TVReply.getText().toString() + ":" + m_ETReply.getText().toString();

  257. params.put("reply", CommentsListActivity.this.m_TVid.getText().toString());

  258. params.put("content", Helper.SmartText(Helper.outToHTML(strReply), 500, false));

  259. }

  260. else

  261. {

  262. params.put("content", Helper.SmartText(Helper.outToHTML(m_ETReply.getText().toString()), 500, false));

  263. }

  264. }

  265. loginService.AsynPost(new HttpUtilService.CallbackListener() {

  266. @Override

  267. public void callback(String result) {

  268. progressDialog.dismiss();

  269. try {

  270. JSONObject obj = new JSONObject(result);

  271. int code = obj.getInt("code");

  272. if( code == 1)

  273. {

  274. Toast ta;

  275. if(CommentsListActivity.this.m_bcomments)

  276. {

  277. CommentsListActivity.this.m_commentObj = new Helper.SmartJSONArray(obj.getJSONArray("data"));

  278. CommentsListActivity.this.initData();

  279. ta = Toast.makeText(CommentsListActivity.this, "获取成功", Toast.LENGTH_LONG);

  280. }

  281. else

  282. {

  283. if(!obj.getString("data").equals("false"))

  284. {

  285. CommentsListActivity.this.addCommentItem(obj.getJSONObject("data"));

  286. }

  287. ta = Toast.makeText(CommentsListActivity.this, "评论成功", Toast.LENGTH_LONG);

  288. }

  289. ta.show();

  290. }

  291. else

  292. {

  293. Toast ta;

  294. if(CommentsListActivity.this.m_bcomments)

  295. ta = Toast.makeText(CommentsListActivity.this, "获取失败:"+code, Toast.LENGTH_LONG);

  296. else

  297. ta = Toast.makeText(CommentsListActivity.this, "评论失败:"+code, Toast.LENGTH_LONG);

  298. ta.show();

  299. }

  300. } catch (JSONException e) {

  301. e.printStackTrace();

  302. Toast toast = Toast.makeText(CommentsListActivity.this, result, Toast.LENGTH_LONG );

  303. toast.show();

  304. }

  305. }

  306. }, CommentsListActivity.this.m_bcomments ? "/api/plan/get_comment" : "/api/plan/comment", params);

  307. }

  308. }

  309. };

  310. OnItemLongClickListener itemLongClick = new OnItemLongClickListener() {

  311. @Override

  312. public boolean onItemLongClick(AdapterView<?> arg0, View view,

  313. final int arg2, long arg3) {

  314. TextView cid = (TextView)view.findViewById(R.id.TVcid);

  315. CommentsListActivity.this.m_replycCmmentID = cid.getText().toString();

  316. TextView reply = (TextView)view.findViewById(R.id.TVcontent);

  317. TextView name = (TextView)view.findViewById(R.id.TVname);

  318. CommentsListActivity.this.m_replyCommentContent = "回复@" + name.getText() + " \"" + Helper.SmartText(reply.getText().toString(), 100, true) + "\"";

  319. return false;//let the window create menu

  320. }

  321. };

点赞
收藏
评论区
推荐文章
blmius blmius
3年前
MySQL:[Err] 1292 - Incorrect datetime value: ‘0000-00-00 00:00:00‘ for column ‘CREATE_TIME‘ at row 1
文章目录问题用navicat导入数据时,报错:原因这是因为当前的MySQL不支持datetime为0的情况。解决修改sql\mode:sql\mode:SQLMode定义了MySQL应支持的SQL语法、数据校验等,这样可以更容易地在不同的环境中使用MySQL。全局s
皕杰报表之UUID
​在我们用皕杰报表工具设计填报报表时,如何在新增行里自动增加id呢?能新增整数排序id吗?目前可以在新增行里自动增加id,但只能用uuid函数增加UUID编码,不能新增整数排序id。uuid函数说明:获取一个UUID,可以在填报表中用来创建数据ID语法:uuid()或uuid(sep)参数说明:sep布尔值,生成的uuid中是否包含分隔符'',缺省为
待兔 待兔
4个月前
手写Java HashMap源码
HashMap的使用教程HashMap的使用教程HashMap的使用教程HashMap的使用教程HashMap的使用教程22
Jacquelyn38 Jacquelyn38
3年前
2020年前端实用代码段,为你的工作保驾护航
有空的时候,自己总结了几个代码段,在开发中也经常使用,谢谢。1、使用解构获取json数据let jsonData  id: 1,status: "OK",data: 'a', 'b';let  id, status, data: number   jsonData;console.log(id, status, number )
Stella981 Stella981
3年前
KVM调整cpu和内存
一.修改kvm虚拟机的配置1、virsheditcentos7找到“memory”和“vcpu”标签,将<namecentos7</name<uuid2220a6d1a36a4fbb8523e078b3dfe795</uuid
Wesley13 Wesley13
3年前
mysql设置时区
mysql设置时区mysql\_query("SETtime\_zone'8:00'")ordie('时区设置失败,请联系管理员!');中国在东8区所以加8方法二:selectcount(user\_id)asdevice,CONVERT\_TZ(FROM\_UNIXTIME(reg\_time),'08:00','0
Wesley13 Wesley13
3年前
00:Java简单了解
浅谈Java之概述Java是SUN(StanfordUniversityNetwork),斯坦福大学网络公司)1995年推出的一门高级编程语言。Java是一种面向Internet的编程语言。随着Java技术在web方面的不断成熟,已经成为Web应用程序的首选开发语言。Java是简单易学,完全面向对象,安全可靠,与平台无关的编程语言。
Stella981 Stella981
3年前
Django中Admin中的一些参数配置
设置在列表中显示的字段,id为django模型默认的主键list_display('id','name','sex','profession','email','qq','phone','status','create_time')设置在列表可编辑字段list_editable
Wesley13 Wesley13
3年前
MySQL部分从库上面因为大量的临时表tmp_table造成慢查询
背景描述Time:20190124T00:08:14.70572408:00User@Host:@Id:Schema:sentrymetaLast_errno:0Killed:0Query_time:0.315758Lock_
Python进阶者 Python进阶者
10个月前
Excel中这日期老是出来00:00:00,怎么用Pandas把这个去除
大家好,我是皮皮。一、前言前几天在Python白银交流群【上海新年人】问了一个Pandas数据筛选的问题。问题如下:这日期老是出来00:00:00,怎么把这个去除。二、实现过程后来【论草莓如何成为冻干莓】给了一个思路和代码如下:pd.toexcel之前把这