试试这个,我已经测试过了,上下文菜单只在长按时调用,onclick 只发生 listview 点击项事件
package com.example.listview;
import android.app.ListActivity;
import android.graphics.Color;
import android.os.Bundle;
import android.util.Log;
import android.view.ContextMenu;
import android.view.ContextMenu.ContextMenuInfo;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.AdapterView.OnItemClickListener;
public class ListViewExampleActivity extends ListActivity {
static final String[] STATES = new String[] { "Haryana", "Punjab", "Rajasthan",
"Maharashtra", "Madhya Pradesh", "Kerala", "Jammu","Bihar","Karnataka" , "TamilNadu",
"Uttar Pradesh" ,"Gujrat"};
View listColor;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setListAdapter(new ArrayAdapter<String>(this, R.layout.main,STATES));
ListView listView = getListView();
listView.setTextFilterEnabled(true);
listView.setBackgroundColor(getTitleColor());
registerForContextMenu(listView);
listView.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
if(listColor!=null){
listColor.setBackgroundColor(Color.BLACK);
listColor=view;
}else{
listColor=view;
}
Log.i("called", "item click");
listColor.setBackgroundColor(Color.BLUE);
//on click of any item the item name will be shown in toast
Toast.makeText(getApplicationContext(),
((TextView) view).getText(), Toast.LENGTH_SHORT).show();
}
});
}
@Override
public void onCreateContextMenu(ContextMenu menu, View v,
ContextMenuInfo menuInfo) {
Log.i("called", "Context menu");
Toast.makeText(getApplicationContext(),
"Context menu", Toast.LENGTH_SHORT).show();
}
}