I have a ListFragment where I would like to add a normal click listener and a long one.
I override the onListItemClick() method on the ListFragment. Here, there is no problem it works.
Then I created an Adapter where I added an OnLongClickListener through setOnLongClickListener() in the getView() method:
public class QuestionsAdapter extends BaseAdapter {
private QuestionsBean questions = null;
private LayoutInflater inflater = null;
public QuestionsAdapter(LayoutInflater inflater) {
this.inflater = inflater;
}
#Override
public int getCount() {
return (questions != null && questions.getQuestionList() != null) ? questions.getQuestionList().size() : 0;
}
#Override
public Object getItem(int position) {
return (questions != null && questions.getQuestionList() != null) ? questions.getQuestionList().get(position) : null;
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder holder;
QuestionBean question = ((QuestionsBean) questions).getQuestionList().get(position);
if (convertView == null) {
holder = new ViewHolder();
convertView = inflater.inflate(R.layout.item_fragment_question, null);
holder.questionItem = (TextView) convertView.findViewById(R.id.itemFragmentQuestions);
holder.questionItem.setOnLongClickListener(new View.OnLongClickListener() {
#Override
public boolean onLongClick(View v) {
System.out.println("test => it works");
;
return false;
}
});
convertView.setTag(holder);
} else {
holder = (ViewHolder) convertView.getTag();
}
holder.questionItem.setText(question.getQuestion());
return convertView;
}
private class ViewHolder {
TextView questionItem;
}
public void setQuestions(QuestionsBean questions) {
List<QuestionBean> temp = new ArrayList<QuestionBean>();
if (questions != null && questions.getQuestionList() != null) {
for (QuestionBean question : questions.getQuestionList()) {
if (question.isActivated()) {
temp.add(question);
}
}
questions.setQuestionList(temp);
}
this.questions = questions;
notifyDataSetChanged();
}
}
Now, the longClickListener works but not the normal click anymore (actually it works like one time out of 10, or 15 or 20 (it depends...).
I have no idea why when I set both listener, the onListItemClick() doesn't work.
Any idea ?
Thanks for you help.
EDIT: My row xml
<TextView
android:id="#+id/itemFragmentQuestions"
style="#style/ItemFragmentQuestion"
android:layout_marginBottom="#dimen/itemFragmentQuestionsMarging"
android:background="#drawable/background_validated" >
</TextView>
</LinearLayout>
EDIT:
My ListFragment class:
public class QuestionsFragment extends ListFragment {
public static final int VALIDATED = 1;
public static final int IN_PROGRESS = 1;
public static final int NON_OBSERVED = 1;
private QuestionsAdapter adapter;
private QuestionsBean questions;
public QuestionsFragment() {
}
public QuestionsFragment(QuestionsBean questions) {
this.questions = questions;
}
public int getShownIndex() {
return getArguments() != null ? getArguments().getInt("index", 0) : 0;
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
this.adapter = new QuestionsAdapter(inflater);
registerForContextMenu(getListView());
View questionsView = (LinearLayout) inflater.inflate(R.layout.fragment_questions, null);
setListAdapter(adapter);
return questionsView;
}
#Override
public void onListItemClick(ListView l, View v, int position, long id) {
super.onListItemClick(l, v, position, id);
if (l == this.getListView()) {
QuestionBean question = (QuestionBean) l.getItemAtPosition(position);
TextView textView = (TextView) v.findViewById(R.id.itemFragmentQuestions);
switch (question.getValue()) {
case QuestionBean.OK:
question.setValue(QuestionBean.NOK);
textView.setBackgroundResource(R.drawable.background_in_progress);
break;
case QuestionBean.NOK:
question.setValue(QuestionBean.NA);
textView.setBackgroundResource(R.drawable.background_non_observed);
break;
case QuestionBean.NA:
question.setValue(QuestionBean.OK);
textView.setBackgroundResource(R.drawable.background_validated);
break;
}
}
}
#Override
public void onResume() {
super.onResume();
refresh(this.questions);
}
public void refresh(QuestionsBean questions) {
this.questions = questions;
adapter.setQuestions(questions);
}
#Override
public void onCreateContextMenu(ContextMenu menu, View v, ContextMenuInfo menuInfo) {
super.onCreateContextMenu(menu, v, menuInfo);
menu.setHeaderTitle("Menu Title");
menu.add(0, v.getId(), 0, "Option 1");
menu.add(0, v.getId(), 0, "Option 2");
}
#Override
public boolean onContextItemSelected(MenuItem item) {
AdapterContextMenuInfo info = (AdapterContextMenuInfo) item.getMenuInfo();
if (item.getTitle() == "Option 1") {
// Option 1 code here
} else if (item.getTitle() == "Option 2") {
// Option 2 code here
}
return super.onContextItemSelected(item);
}
}
#Barak As you can see, I set the Adapter in onCreateView() and when I put registerForContextMenu(getListView()) right after, I get an error. It seems that getListView() isn't set yet.
Why not use a context menu for the long click rather than muck about in the adapter?
registerForContextMenu(getListView());
and then:
#Override
public void onCreateContextMenu(ContextMenu menu, View v, ContextMenuInfo menuInfo) {
super.onCreateContextMenu(menu, v, menuInfo);
menu.setHeaderTitle("Menu Title");
menu.add(0, v.getId(), 0, "Option 1");
menu.add(0, v.getId(), 0, "Option 2");
}
#Override
public boolean onContextItemSelected(MenuItem item) {
AdapterContextMenuInfo info = (AdapterContextMenuInfo) item.getMenuInfo();
if (item.getTitle().equals("Option 1")) {
// Option 1 code here
} else if (item.getTitle().equals("Option 2")) {
// Option 2 code here
}
return super.onContextItemSelected(item);
}
I think you should use listView.setOnItemLongClickListener(...); instead of listView.setOnLongClickListener(...);.
Sorry for tearing up healing wounds :-)
Related
I'm having an issue with a long press on a row to get highlighted.
I looked over how to handle the single click to lead to another activity and a long press to get the contextual action bar comes up. I decided to switch the listview choice by ListView.CHOICE_MODE_MULTIPLE_MODAL and ListView.CHOICE_MODE_NONE to let the built in android methods to do their work on selected rows. The single click is working as it is intended.
The multiple modal is working and the contextual action bar is showing the number of the notes selected yet the rows aren't highlighted. I have checked the theme and it doesn't work either for Theme.AppCompat and Theme.AppCompat.Light.
Here are the code -
Classes
MainActivity extends AppCompatActivity {}
ObjectListFragment extends ListFragment implements
AdapterView.OnItemLongClickListener, AbsListView.MultiChoiceModeListener {}
NoteListAdapter extends ArrayAdapter<NoteTO> {}
initialization of listeners and other objects in ListFragment
//get the data
#Override
public void onViewCreated(View view, Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
LogUtils.LOGD(getClass().getSimpleName(), "onViewCreated");
ListView listView = getListView();
listView.setOnItemLongClickListener(this);
listView.setMultiChoiceModeListener(this);
int choiceMode = (savedInstanceState == null ? ListView.CHOICE_MODE_NONE : savedInstanceState.getInt(STATE_CHOICE_MODE));
listView.setChoiceMode(choiceMode);
}
Action mode methods, long press method and private methods
#Override
public void onListItemClick(ListView l, View v, int position, long id) {
l.setItemChecked(position, true);
NoteTO note = (NoteTO) l.getItemAtPosition(position);
Intent i = new Intent(getActivity(), NoteActivity.class);
NotePreferences.setNote(getActivity(), note);
AppPreferences.setActionFlag(getActivity(), AppConstants.ACTION_UPDATE);
startActivityForResult(i, 1);
}
#Override
public void onItemCheckedStateChanged(ActionMode actionMode, int i, long l, boolean b) {
if (mActiveMode != null) {
updateSubtitle(actionMode);
}
}
#Override
public boolean onCreateActionMode(ActionMode actionMode, Menu menu) {
MenuInflater inflater = getActivity().getMenuInflater();
inflater.inflate(R.menu.contextual_menu, menu);
this.mActiveMode = actionMode;
updateSubtitle(mActiveMode);
return true;
}
#Override
public boolean onPrepareActionMode(ActionMode actionMode, Menu menu) {
return false;
}
#Override
public boolean onActionItemClicked(ActionMode actionMode, MenuItem menuItem) {
boolean result = performActions(menuItem);
updateSubtitle(mActiveMode);
return(result);
}
#Override
public void onDestroyActionMode(ActionMode actionMode) {
if (mActiveMode != null) {
mActiveMode = null;
getListView().setChoiceMode(ListView.CHOICE_MODE_NONE);
getListView().setAdapter(getListView().getAdapter());
}
}
public boolean performActions(MenuItem item) {
List<NoteTO> list = listAdapter.getList();
Set<Integer> positionSet = listAdapter.getCurrentCheckedPosition();
Integer[] positions = listAdapter.getCurrentCheckedPosition().toArray(new Integer[positionSet.size()]);
if(item.getItemId() == R.id.item_delete) {
List<NoteTO> notesToBeDeleted = new ArrayList<NoteTO>();
String text = "";
for(int i = 0; i < positions.length; i++) {
NoteTO note = (NoteTO) list.get(positions[i]);
notesToBeDeleted.add(note);
}
task = new ObjectListFragment.deleteNotesTask().execute(notesToBeDeleted);
return true;
}
else if(item.getItemId() == R.id.item_share) {
String text = "";
for(int i = 0; i < positions.length; i++) {
NoteTO note = (NoteTO) list.get(positions[i]);
text = text + note.getBody() + "\r\n"+ "\r\n";
}
shareNotes(text);
return true;
}
return false;
}
private void updateSubtitle(ActionMode mode) {
mode.setSubtitle("(" + getListView().getCheckedItemCount() + ")");
}
#Override
public boolean onItemLongClick(AdapterView<?> adapterView, View view, int position, long id) {
getListView().setChoiceMode(ListView.CHOICE_MODE_MULTIPLE_MODAL);
getListView().setItemChecked(position, true);
return(true);
}
Adapter - there isn't any code that overwrite up the selectors of the rows.
#NonNull
#Override
public View getView(int position, #Nullable View convertView, #NonNull ViewGroup parent) {
View row = super.getView(position, convertView, parent);
NoteHolder holder = (NoteHolder) row.getTag();
if(holder == null) {
holder = new NoteHolder(row);
row.setTag(holder);
}
NoteTO note = getItem(position);
if(mSettings.getListSingleLine() == 0) {
holder.textviewNote.setEllipsize(null);
holder.textviewNote.setSingleLine(false);
}
else {
holder.textviewNote.setEllipsize(TextUtils.TruncateAt.END);
holder.textviewNote.setSingleLine();
}
holder.textviewNote.setText(note.getBody());
holder.textviewNote.setTextSize(getmSettings().getListViewTextSize());
holder.textviewNote.setTypeface(getmSettings().getGeneralFontStyleTypeFace());
//holder.textviewNote.setBackgroundColor(ContextCompat.getColor(context, android.R.color.background_dark));
//holder.textviewNote.setBackground(selector);
//arraylist has containers to get the boolean of the position
if (mSelection.get(position) != null) {
//holder.textviewNote.setSelected(true);
//holder.textviewNote.setBackgroundColor(ContextCompat.getColor(context, android.R.color.holo_blue_light));
//holder.textviewNote.setTextColor(mSettings.getListViewTextColor());
//holder.textviewNote.setBackground(selector);
}
return row;
}
I found the solution, I overlooked the styles where will get the highlighted rows -
<item name="android:background">?android:attr/activatedBackgroundIndicator</item>
Thanks to
Highlight custom listview item when long click
and
Commonsware - The Busy Coder's Guide to Android Development
I have a ListView. This ListView has an array and the array has 5 numbers. First of all, in the first activity the user selects 5 numbers and theses 5 number go in the ListView in the second activity. I want to start an Intent with theses 5 numbers when the user click on any number on the Context menu. The intent will start that position. But why cant I get the selected number?
public class AnaMenu extends AppCompatActivity {
public static final int MENU_Ara = Menu.FIRST+1;
int sayı = 50;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_ana_menu);
ListView liste = (ListView) findViewById(R.id.oyun);
OyunTextView oyunTextView = new OyunTextView();
liste.setAdapter(oyunTextView);
registerForContextMenu(liste);
}
class OyunTextView extends BaseAdapter {
#Override
public int getCount() {
Intent i = getIntent();
final ArrayList<String> secilmis = i.getStringArrayListExtra("listem");
return secilmis.size();
}
#Override
public Object getItem(int position) {
return null;
}
#Override
public long getItemId(int position) {
return 0;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
convertView = getLayoutInflater().inflate(R.layout.oyuntextview , null);
TextView namesbox = (TextView)convertView.findViewById(R.id.isim);
TextView sayılar = (TextView)convertView.findViewById(R.id.sayı);
Intent i = getIntent();
final ArrayList<String> secilmis = i.getStringArrayListExtra("listem");
namesbox.setText(secilmis.get(position));
sayılar.setText(String.valueOf(sayı));
if (sayı == 50) {
sayılar.setTextColor(getResources().getColor(R.color.elli));}
return convertView;
}
}
#Override
public void onCreateContextMenu(ContextMenu menu, View v, ContextMenu.ContextMenuInfo menuInfo) {
menu.add(Menu.NONE, MENU_Ara, Menu.NONE, "Ara");
super.onCreateContextMenu(menu, v, menuInfo);
}
#Override
public boolean onContextItemSelected(MenuItem item) {
AdapterView.AdapterContextMenuInfo info = (AdapterView.AdapterContextMenuInfo) item.getMenuInfo();
Intent i = getIntent();
secilmis = i.getStringArrayListExtra("listem");
switch (item.getItemId()) {
case MENU_Ara:
Intent ara = new Intent(Intent.ACTION_DIAL);
ara.setData(Uri.parse());
startActivity(ara);
return true;
}
return super.onContextItemSelected(item);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater menuInflater = getMenuInflater();
menuInflater.inflate(R.menu.mains,menu);
return super.onCreateOptionsMenu(menu);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.action_browse :ayar();return true;
case R.id.backbut: geri();return true;
}
return super.onOptionsItemSelected(item);
}
private void ayar() {
Intent i = new Intent(AnaMenu.this, Ayarlar.class);
startActivity(i);
}
private void geri() {
Intent ii = new Intent(AnaMenu.this, MainActivity.class);
startActivity(ii);
AnaMenu.this.finish();
}
}
}
You can use arraylistname.get(position) in the onItemClickListener method to get the position of the selected item.
I'm quite new at Android developing and I was trying to put a a context menu on my Listview that uses a CursorAdapter, I followed this examples https://www.youtube.com/watch?v=Pq9YQl0nfEk Using contextmenu with listview in android but the menu doesn't appear and I don't no why, appearently everything's OK.
These is the code of my activity
public class ProductsView extends AppCompatActivity {
private FloatingActionButton botonAnadir;
private ListView lvProducts;
SetOfProductList mylist;
private ProductAdapter productAdapter;
Cursor cursor;
private ProductList productList;
private Long idProductList;
private DBManager dbManager;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Bundle bundle = getIntent().getExtras();
if (bundle != null){
productList = bundle.getParcelable("productList");
setTitle(getResources().getString(R.string.show_products) + " " + productList.getName());
}
setContentView(R.layout.products_view);
initialize();
}
private void initialize(){
botonAnadir = (FloatingActionButton)findViewById(R.id.button_add_product);
lvProducts = (ListView)findViewById(R.id.listViewProducts);
dbManager = new DBManager(getApplicationContext());
loadProducts();
registerForContextMenu(lvProducts);
botonAnadir.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
creaNuevaLista();
}
});
lvProducts.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Product aux = getProduct(position);
goToNewProduct(aux);
}
});
lvProducts.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
#Override
public boolean onItemLongClick(AdapterView<?> parent, View view, int position, long id) {
// markAsPurchased(position);
return true;
}
});
}
private void markAsPurchased(int position){
Product p = getProduct(position);
TextView item = (TextView) findViewById(R.id.textview_product_name);
if (p.getPurchased() == 0){
p.setPurchased(1); //mark as a purchased
item.setPaintFlags(item.getPaintFlags() | Paint.STRIKE_THRU_TEXT_FLAG);
}
else{
p.setPurchased(0); //mark as a purchased
item.setPaintFlags(item.getPaintFlags() & (~Paint.STRIKE_THRU_TEXT_FLAG));
}
editProduct(p); //makes de update
loadProducts();
}
private void editProduct(Product product){
dbManager.updateProduct(product);
}
private void goToNewProduct(Product p){
Intent intent = new Intent(this,NewProductActivity.class);
Bundle b = new Bundle();
b.putBoolean("editMode",true);
b.putParcelable("product", p);
intent.putExtras(b);
startActivity(intent);
}
private void creaNuevaLista(){
Intent i = new Intent(this,NewProductActivity.class);
Bundle b = new Bundle();
b.putParcelable("productList", productList);
i.putExtras(b);
startActivityForResult(i, 0);
}
private void loadProducts(){
cursor = dbManager.getAllProductsWithCursor(productList);
productAdapter = new ProductAdapter(this,cursor);
lvProducts.setAdapter(productAdapter);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
#Override
public void onCreateContextMenu(ContextMenu menu, View v, ContextMenu.ContextMenuInfo menuInfo) {
super.onCreateContextMenu(menu, v, menuInfo);
if (v.getId() == R.id.listViewProducts){
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.prodcut_view_context_menu,menu);
}
}
#Override
public boolean onContextItemSelected(MenuItem item) {
AdapterView.AdapterContextMenuInfo info = (AdapterView.AdapterContextMenuInfo) item.getMenuInfo();
switch (item.getItemId()){
case R.id.delete_id:
return true;
default:
return super.onContextItemSelected(item);
}
}
}
And this is the adapter that I'm using
public class ProductAdapter extends CursorAdapter {
private LayoutInflater inflater;
//Constructor
public ProductAdapter(Context context, Cursor cursor) {
super(context, cursor,false);
}
// The newView method is used to inflate a new view and return it,
// you don't bind any data to the view at this point.
#Override
public View newView(Context context, Cursor cursor, ViewGroup parent) {
inflater = (LayoutInflater) context.getSystemService(context.LAYOUT_INFLATER_SERVICE);
View view = inflater.inflate(R.layout.layout_product_row,parent,false);
return view;
}
// The bindView method is used to bind all data to a given view
// such as setting the text on a TextView.
#Override
public void bindView(View view, Context context, Cursor cursor) {
TextView tv_product_name = (TextView) view.findViewById(R.id.textview_product_name); // Find fields to populate in inflated template
String product_name = cursor.getString(cursor.getColumnIndexOrThrow("name"));// Extract properties from cursor
// Populate fields with extracted properties
tv_product_name.setText(product_name);
if (cursor.getInt(cursor.getColumnIndexOrThrow("purchased")) == 1){
tv_product_name.setPaintFlags(tv_product_name.getPaintFlags() | Paint.STRIKE_THRU_TEXT_FLAG);
}
}
public Product getProduct(int position, Cursor cursor) {
Product p=null;
if(cursor.moveToPosition(position)) {
Log.e("PRODUCTLISTADAPTER","nombre es: "+cursor.getString(cursor.getColumnIndex("name")));
p = new Product (cursor.getLong(cursor.getColumnIndex("_id")),cursor.getString(cursor.getColumnIndex("name")),
cursor.getString(cursor.getColumnIndex("unit_type")),cursor.getDouble(cursor.getColumnIndex("value")),cursor.getInt(cursor.getColumnIndex("purchased")),cursor.getLong(cursor.getColumnIndex("id_pl")));
}
return p;
}
}
Can anyone exaplin me why it isn't working? isn't it necessary to make something on the LongClickListener ? because I don't see that the menu is being created.
Thanks in advance.
You've set an OnItemLongClickListener for the ListView, which will run before the context Menu is created. Returning true from its onItemLongClick() method indicates that the long click is being consumed there, so the Menu will not be created.
If you don't actually need the OnItemLongClickListener, you can remove the relevant code. If you do need it as well, for some reason, you can return false from onItemLongClick(), and your Menu will then show.
I have a listview with a custon adapter. I have to put a context menu for it, but it's not working. And I put the onItemLongClick to the list and it's not working too. I don't know how to trigger the contextmenu. If I have to click on an item or long click on it. I do register a long click to get the id from the item.
EDIT I think i figure out whats the problem. I have a button on my item listview. I remove this button from the layout and the context menu worked fine. But I need this button. Why the button was causing problem in the context menu?
This is the class:
public class HistoricoDespesasActivity extends Activity {
Helper h;
AlphaAnimation buttonClick;
DespesasDAO dDAO;
ListView lv;
DespesaHistoricoAdapter adapter;
int idDespesasSelecionada;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_historico_despesas);
lv = (ListView)findViewById(R.id.lvHistoricoDespesas);
TextView tvMarcaModelo = (TextView)findViewById(R.id.tvMarcaModeloCabecalho);
TextView tvApelido = (TextView)findViewById(R.id.tvApelidoCabecalho);
tvApelido.setVisibility(View.INVISIBLE);
tvMarcaModelo.setVisibility(View.INVISIBLE);
buttonClick = new AlphaAnimation(1, 0.5f);
h = new Helper(this);
h.mostraVeiculoAtivo();
adapter = new DespesaHistoricoAdapter(this);
dDAO = new DespesasDAO(this);
dDAO.open();
Cursor cursor = dDAO.consultarTodasDespesasByIdVeiculo(h.getId());
int id;
String data;
String tipoDespesa = null;
double valor;
int tipo = 0;
if(cursor != null && cursor.moveToFirst()){
do {
id = cursor.getInt(cursor.getColumnIndex(DespesasDAO.COLUNA_ID));
data = cursor.getString(cursor.getColumnIndex(DespesasDAO.COLUNA_DESPESA_DATA));
tipo = cursor.getInt(cursor.getColumnIndex(DespesasDAO.COLUNA_ITEM_ID));
valor = cursor.getDouble(cursor.getColumnIndex(DespesasDAO.COLUNA_DESPESA_VALOR));
if(tipo == 1){
tipoDespesa = "Pedágio";
} else if(tipo == 2){
tipoDespesa = "Estacionamento";
} else if(tipo == 3){
tipoDespesa = "Lavagem";
} else if(tipo == 4){
tipoDespesa = "Diversos";
}
adapter.addDespesa(id, tipoDespesa, data, valor);
} while (cursor.moveToNext());
cursor.close();
dDAO.close();
lv.setAdapter(adapter);
}
lv.setLongClickable(true);
lv.setOnItemLongClickListener(new OnItemLongClickListener() {
#Override
public boolean onItemLongClick(AdapterView<?> parent, View view,
int position, long id) {
idDespesasSelecionada = (Integer) parent.getItemAtPosition(position);
return true;
}
});
registerForContextMenu(lv);
}
#Override
public void onCreateContextMenu(ContextMenu menu, View v,
ContextMenuInfo menuInfo) {
super.onCreateContextMenu(menu, v, menuInfo);
menu.setHeaderTitle("Despesas");
menu.add(0, v.getId(), 0, "Deletar");
}
#Override
public boolean onContextItemSelected(MenuItem item) {
if(item.getTitle().equals("Deletar")){
dDAO.open();
dDAO.removerDespesasById(idDespesasSelecionada);
dDAO.close();
}
onCreate(new Bundle());
return super.onContextItemSelected(item);
}
#Override
protected void onResume() {
onCreate(new Bundle());
super.onResume();
}
}
Remove your setOnItemLongClickListener of listView and replace onContextItemSelected with this
#Override
public boolean onContextItemSelected(MenuItem item)
{
AdapterContextMenuInfo info = (AdapterContextMenuInfo) item.getMenuInfo();
if(item.getTitle().equals("Deletar"))
{
dDAO.open();
dDAO.removerDespesasById(info.position);
dDAO.close();
}
return true;
}
change onCreateContextMenu like this :
#Override
public void onCreateContextMenu(ContextMenu menu, View v,ContextMenuInfo menuInfo) {
super.onCreateContextMenu(menu, v, menuInfo);
MenuInflater inflater =getMenuInflater();
inflater.inflate(R.menu.more_tab_menu, menu);
}
see this topic :
Android, How to create Context Menu...
EDIT :
use button. image Button and list view is clickable. if you use Button and set android:focusable="false" android:focusableInTouchMode="false" work fine.
I have a list activity, and I chose to manually add the first item which is "add new item...".
I have registered the context menu for the whole listview, using registerForContextMenu(getListView()); straight into the onCreate.
When the context menu is build, the system calls onCreateContextMenu(ContextMenu menu, View v, ContextMenuInfo menuInfo). The View v is the listView, and I cannot find a way to know which item in the listview is being long-pressed.
I could create a xml layout, with a layout for the "add new item..." and add a listview after, which would be populated by the activity, and that would react to the context menu, but I'm sure there is a way to solve this problem without any xml layout.
I have tried to register each view inside my listview using registerForContextMenu, which works, however the listview doesn't respond to touch anymore.
Here is my activity code listing:
public class AMain extends ListActivity {
private List<String> pregList;
private List<Long> pregIds;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
pregList = new ArrayList<String>();
pregIds = new ArrayList<Long>();
registerForContextMenu(getListView());
}
#Override
public void onCreateContextMenu(ContextMenu menu, View v, ContextMenuInfo menuInfo) {
super.onCreateContextMenu(menu, v, menuInfo);
// TODO: hide the menu for the 1st item!!
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.context_menu, menu);
}
#Override
public boolean onContextItemSelected(MenuItem item) {
AdapterContextMenuInfo info = (AdapterContextMenuInfo) item.getMenuInfo();
Logger.d("id = "+info.id);
switch (item.getItemId()) {
case R.id.menu_show:
showPregnancy((int) info.id);
return true;
case R.id.menu_edit:
editPregnancy((int) info.id);
return true;
case R.id.menu_delete:
//TODO: do the deletion
return true;
default:
return super.onContextItemSelected(item);
}
}
protected void onStart() {
super.onStart();
clearPregList();
loadPregList();
getListView().setAdapter(new PregnancyListAdapter(this));
}
void clearPregList() {
pregList.clear();
pregIds.clear();
}
void loadPregList() {
PregnanciesDbAdapter db = new PregnanciesDbAdapter(this);
db.open();
Cursor c = db.getPregnancies();
if (c != null) {
do {
pregList.add(c.getString(c.getColumnIndex(PregnanciesDbAdapter.KEY_PREG_NOM)));
pregIds.add(c.getLong(c.getColumnIndex(PregnanciesDbAdapter.KEY_PREG_ROWID)));
} while (c.moveToNext());
c.close();
}
db.close();
}
private class PregnancyListAdapter extends BaseAdapter {
private Context context;
public PregnancyListAdapter(Context ctx) {
context = ctx;
}
#Override
public int getCount() {
return pregList.size()+1;
}
#Override
public Object getItem(int position) {
if (position == 0) { // add button
return getString(R.string.addPreg);
} else {
return pregList.get(position-1);
}
}
#Override
public long getItemId(int position) {
if (position == 0) {
return -1;
}
return pregIds.get(position-1);
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
LinearLayout itemLayout;
itemLayout= (LinearLayout) LayoutInflater.from(context).inflate(R.layout.homelist_item_pregnancy, parent, false);
ImageView logo = (ImageView) itemLayout.findViewById(R.id.logo);
TextView pregName = (TextView) itemLayout.findViewById(R.id.pregName);
if (position == 0) {
itemLayout.setFocusable(false);
itemLayout.setFocusableInTouchMode(false);
pregName.setText(getString(R.string.addPreg));
} else {
logo.setVisibility(View.INVISIBLE);
pregName.setText(pregList.get(position-1));
}
itemLayout.setId(position);
return itemLayout;
}
}
#Override
protected void onListItemClick(ListView l, View v, int position, long id) {
super.onListItemClick(l, v, position, id);
if (position == 0) {
startActivity(prepareIntent(AShowPregnancy.class, 0));
} else {
showPregnancy(position-1);
}
}
void showPregnancy(int pregId) {
startActivity(prepareIntent(AShowPregnancy.class, pregId));
}
void editPregnancy(int pregId) {
startActivity(prepareIntent(ANewPregnancy.class, pregId));
}
Intent prepareIntent(Class<?> className, int pregId) {
Intent i = new Intent(this, className);
if (pregId > 0) {
PregnanciesDbAdapter db = new PregnanciesDbAdapter(this);
db.open();
Pregnancy p = db.load(pregIds.get(pregId));
db.close();
i.putExtra(C.EXTRA_PREGNANCY, p);
}
return i;
}
}
Thanks for reading. Hope you can help.
Oh, god, again. I found out myself how to do it, and it was easier than easy.
AdapterContextMenuInfo info = (AdapterContextMenuInfo) menuInfo;
// info.position is the position in the ListView
I hate myself :)