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

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

思路就是

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

就这么简单。





import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.Map;

import org.json.JSONException;
import org.json.JSONObject;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.res.Resources;
import android.graphics.Color;
import android.os.Bundle;
import android.text.Spannable;
import android.text.SpannableStringBuilder;
import android.text.style.ForegroundColorSpan;
import android.util.Log;
import android.view.ContextMenu;
import android.view.ContextMenu.ContextMenuInfo;
import android.view.LayoutInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnCreateContextMenuListener;
import android.view.ViewGroup;
import android.view.Window;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.AdapterView.OnItemLongClickListener;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

public class CommentsListActivity extends Activity
{
	
	private String m_jid = "0";
	private ListView m_listView;
	private EditText m_ETReply;
	private Appdata m_appdata;
	private TextView m_TVReply;
	private TextView m_TVid;
	private LinearLayout m_ReplyArea;
	private String m_replycCmmentID = "";
	private String m_replyCommentContent = "";
	private boolean m_bcomments = false;
	private ArrayList<JSONObject> m_commentList = new ArrayList<JSONObject>();
	private Helper.SmartJSONArray m_commentObj = null;
	 public void onCreate(Bundle savedInstanceState) 
	 {
	        super.onCreate(savedInstanceState);
	        requestWindowFeature(Window.FEATURE_CUSTOM_TITLE);
	        setContentView(R.layout.comments);
	        getWindow().setFeatureInt(Window.FEATURE_CUSTOM_TITLE,
	                R.layout.title);
	        m_appdata = (Appdata)this.getApplicationContext();
	        m_listView = (ListView)this.findViewById(R.id.listViewShow);
	        m_ETReply = (EditText)this.findViewById(R.id.editTextComment);
	        m_ReplyArea = (LinearLayout)this.findViewById(R.id.ReplyArea);
	        m_TVReply = (TextView)m_ReplyArea.findViewById(R.id.TVReply);
  	        m_TVid = (TextView)this.findViewById(R.id.TVid);
	        Button btnBefore = (Button)this.findViewById(R.id.btn_before);
	        btnBefore.setText(R.string.back);
	        btnBefore.setVisibility(View.VISIBLE);
	        Intent intentFrom = this.getIntent();
	        Bundle bd = intentFrom.getExtras();
	        this.m_jid = bd.getString("jid");
	        TextView viewTitle = (TextView)this.findViewById(R.id.app_title);
	    	viewTitle.setText("\"" + Helper.SmartText(bd.getString("title"), 10, true) + "\"的评论");
	        IntentFilter intentFilter= new IntentFilter();
	        intentFilter.addAction(Helper.INTENAL_ACTION_GETPLANCOMMENTS);
	        registerReceiver(br,intentFilter);	        
	        Intent intent= new Intent(Helper.INTENAL_ACTION_GETPLANCOMMENTS);
			sendBroadcast(intent);
			onLongClickListView();
	 }
	 
	 @Override
	    public void onDestroy()
	    {
	    	super.onDestroy();
	    	unregisterReceiver(br);
	    }
	 
	 class SortByTime implements Comparator<JSONObject> {
    	 public int compare(JSONObject o1, JSONObject o2) {
    	  try {
			if (Helper.getDiffDays(o1.getString("time"), o2.getString("time")) < 0)
			   return 1;
		} catch (JSONException e) {
			e.printStackTrace();
		}
    	  return 0;
    	 }
    	}
	 
	 public void comment(View v)
	 {
		 IntentFilter intentFilter= new IntentFilter();
		 intentFilter.addAction(Helper.INTENAL_ACTION_GETPLANDOCOMMENT);
		 registerReceiver(br,intentFilter);
		 Intent intent= new Intent(Helper.INTENAL_ACTION_GETPLANDOCOMMENT);
		 sendBroadcast(intent);
	 }
	 
	 public void doBefore(View v)
	 {
		 CommentsListActivity.this.finish();
	 }
	 
	 void onLongClickListView()
	 {
		 m_listView.setOnItemLongClickListener(itemLongClick);
		 registerForContextMenu(m_listView);  
	 }
	 public void onCreateContextMenu(ContextMenu menu, View v,   
             ContextMenuInfo menuInfo) {
		 super.onCreateContextMenu(menu, v, menuInfo);
		 menu.add(0,0,0,"回复评论");
		 }   
	 
	 @Override       
	    public boolean onContextItemSelected(MenuItem aItem) {       
	         ContextMenuInfo menuInfo = (ContextMenuInfo) aItem.getMenuInfo(); 
	         Toast ta;
	         ta = Toast.makeText(CommentsListActivity.this, "onContextItemSelected", Toast.LENGTH_LONG);
	         ta.show();
	         /* Switch on the ID of the item, to get what the user selected. */       
	         switch (aItem.getItemId()) {       
	              case 0:
	            	  
	            	  if(!CommentsListActivity.this.m_replycCmmentID.equals(""))
	            	  {
	            		  CommentsListActivity.this.m_ReplyArea.setVisibility(View.VISIBLE);
	            		  CommentsListActivity.this.m_TVReply.setText(this.m_replyCommentContent);
	            		  CommentsListActivity.this.m_TVid.setText(m_replycCmmentID);
	            	  }
	                   return true;   
	         }       
	         return false;       
	    }       
	 
	 void initData()
	 {
		 int diarycount = this.m_commentObj.getLength();
		 if( diarycount >= 1)
	    	{
			for (int i = 0; i < diarycount; i++)
	    		{
	    			this.m_commentList.add(this.m_commentObj.getObj(i));
	    		}
	    		Collections.sort(this.m_commentList, new SortByTime());
	    	}
	    	
		 CommentItemAdapter dia = new CommentItemAdapter(this);
		 m_listView.setAdapter(dia);
	 }
	 
	 void addCommentItem(JSONObject objCommentItem)
	 {
		 try {
			objCommentItem.put("from_nick", objCommentItem.getString("user_name"));
		} catch (JSONException e) {
			e.printStackTrace();
		}
		 m_ETReply.setText("");
		 this.m_commentList.add(0, objCommentItem);
		 CommentItemAdapter adp = (CommentItemAdapter)m_listView.getAdapter();
		 adp.notifyDataSetChanged();
		 m_listView.setFocusable(true);
	 }
	 
	 public class CommentData
	 {
	    	public TextView TVname;
	    	public TextView TVtime;
	    	public TextView TVcontent;
	    	public TextView TVcid;
	 }
	    
	    public class CommentItemAdapter extends BaseAdapter
	    {
	    	private LayoutInflater mInflater;
	    	public CommentItemAdapter(Context context)
	    	{
	    		this.mInflater = LayoutInflater.from(context);
	    		
	        }
	    	public View getConvertView(int i)
	    	{
	    		View view = mInflater.inflate(getItemViewType(i), null);
	    		CommentData item = new CommentData();
	            item.TVname = (TextView)view.findViewById(R.id.TVname); 
	            item.TVtime = (TextView)view.findViewById(R.id.TVtime); 
	            item.TVcontent = (TextView)view.findViewById(R.id.TVcontent);
	            item.TVcid = (TextView)view.findViewById(R.id.TVcid);
	            view.setTag(item);
	            return view;
	    	}
	    	
	        @Override
	        public int getCount() {
	            return CommentsListActivity.this.m_commentList.size(); 
	        }
	        
	        @Override
	        public int getItemViewType(int position) {
	            return R.layout.listview_item_comment;
	        }
	  
	        @Override
	        public Map<String,Object> getItem(int arg0) { 
	            return null; 
	        } 
	  
	        @Override
	        public long getItemId(int arg0) {
	            return arg0; 
	        } 
	  
	        @Override
	        public View getView(int position, View convertView, ViewGroup parent) {
	        	View view = null;
	        	if(convertView == null)
	        	{
	        		view = getConvertView(position);
	        	}
	        	else
	        	{
	        		view = convertView;
	        	}
	        	CommentData item = (CommentData)view.getTag();
				try {
					JSONObject obj = CommentsListActivity.this.m_commentList.get(position);
					String strTime = obj.getString("time");
					item.TVtime.setText(strTime);					
					item.TVcontent.setText(Helper.outToTextArea(obj.getString("content")));
					String str = obj.getString("from_nick");
					item.TVname.setText(str);
					item.TVcid.setText(obj.getString("id"));
				} catch (JSONException e) {
					e.printStackTrace();
				}
	            return view; 
	        }
	    }
	    
	    private BroadcastReceiver br = new BroadcastReceiver() {
	        @Override
	        public void onReceive(Context context, Intent intent) {
	            String action = intent.getAction();
	            m_bcomments = action.equals(Helper.INTENAL_ACTION_GETPLANCOMMENTS);
	            boolean cdocomment = action.equals(Helper.INTENAL_ACTION_GETPLANDOCOMMENT);
	            if( m_bcomments || cdocomment){
	            	final ProgressDialog progressDialog = ProgressDialog.show(CommentsListActivity.this, null, "亲,稍等片刻哦...", true, false); 
	                progressDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
	                HttpUtilService loginService = new HttpUtilService(CommentsListActivity.this.m_appdata.getToken());
	                Map<String, String> params = new HashMap<String, String>() ;
	                if(m_bcomments)
	                {
	                	params.put("jid", CommentsListActivity.this.m_jid);
		                params.put("page", "1");
	                }
	                else
	                {
	                	params.put("id", CommentsListActivity.this.m_jid);
		                params.put("title", "null");
		                if(CommentsListActivity.this.m_ReplyArea.getVisibility() == View.VISIBLE)
		                {
		                	String strReply = m_TVReply.getText().toString() + ":" + m_ETReply.getText().toString();
		                	params.put("reply", CommentsListActivity.this.m_TVid.getText().toString());
		                	params.put("content", Helper.SmartText(Helper.outToHTML(strReply), 500, false));
		                }
		                else
		                {
		                	params.put("content", Helper.SmartText(Helper.outToHTML(m_ETReply.getText().toString()), 500, false));
		                }
		                
	                }
	                
	                loginService.AsynPost(new HttpUtilService.CallbackListener() {
	        			@Override
	        			public void callback(String result) {
	        				progressDialog.dismiss();
	        				try {
	        					JSONObject obj = new JSONObject(result);
	        					int code = obj.getInt("code");
	        					if( code == 1)
	        					{
	        						Toast ta;
	        						if(CommentsListActivity.this.m_bcomments)
	        						{
	        							CommentsListActivity.this.m_commentObj = new Helper.SmartJSONArray(obj.getJSONArray("data"));     						
		        						CommentsListActivity.this.initData();
		        						ta = Toast.makeText(CommentsListActivity.this, "获取成功", Toast.LENGTH_LONG);
	        						}
	        						else
	        						{
	        							if(!obj.getString("data").equals("false"))
	        							{
	        								CommentsListActivity.this.addCommentItem(obj.getJSONObject("data"));
	        							}
		        						ta = Toast.makeText(CommentsListActivity.this, "评论成功", Toast.LENGTH_LONG);
	        						}
	        						ta.show();
	        					}
	        					else
	        					{
	        						Toast ta;
	        						if(CommentsListActivity.this.m_bcomments)
	        							ta = Toast.makeText(CommentsListActivity.this, "获取失败:"+code, Toast.LENGTH_LONG);
	        						else
	        							ta = Toast.makeText(CommentsListActivity.this, "评论失败:"+code, Toast.LENGTH_LONG);
	        						ta.show();
	        					}
	        				} catch (JSONException e) {
	        					e.printStackTrace();
	            				Toast toast = Toast.makeText(CommentsListActivity.this, result, Toast.LENGTH_LONG );
	            				toast.show();
	        				}
	        			}
	        		}, CommentsListActivity.this.m_bcomments ? "/api/plan/get_comment" : "/api/plan/comment", params);
	            }
	         
	        }
	    };
	    
	    OnItemLongClickListener itemLongClick = new OnItemLongClickListener() {

	    	@Override
	    	public boolean onItemLongClick(AdapterView<?> arg0, View view,
	    	final int arg2, long arg3) {
	        	TextView cid = (TextView)view.findViewById(R.id.TVcid);
	        	CommentsListActivity.this.m_replycCmmentID = cid.getText().toString();
	        	TextView reply = (TextView)view.findViewById(R.id.TVcontent);
	        	TextView name = (TextView)view.findViewById(R.id.TVname);
	        	CommentsListActivity.this.m_replyCommentContent = "回复@" + name.getText() + " \"" + Helper.SmartText(reply.getText().toString(), 100, true) + "\"";
	    		return false;//let the window create menu
	    	}
	    };
	   
}


评论 4
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值