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

2019独角兽企业重金招聘Python工程师标准>>> hot3.png

看了很多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 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 params = new HashMap() ;
  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. };

转载于:https://my.oschina.net/u/1014520/blog/181234

你可能感兴趣的:(Android ListView长按事件弹出菜单并获取选中的item)