I have created a context menu. The context menu appears, when I do a longclick on the listitems. So far so good...
But when i click on a contextitem, nothing happens. Does anyone know this issue?
What's the problem here?
Button for opening the dialog with listview:
Button cmd_fav = (Button) findViewById(R.id.cmd_main_fav);
cmd_fav.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
List<String> valueList = new ArrayList<String>();
db = SQLiteDatabase.openDatabase("/data/data/spicysoftware.abugrundwissen/databases/questions", null,
SQLiteDatabase.OPEN_READWRITE);
Cursor c_ = db.rawQuery("SELECT question, _id, answer FROM tbl_questions"+
" where favourite = 1", null);
if (c_ != null ) {
if (c_.moveToFirst()) {
do {
String str_question = c_.getString(c_.getColumnIndex("question"));
valueList.add(str_question);
} while (c_.moveToNext());
}
// custom dialog
dialog = new Dialog(MainSite.this);
dialog.setContentView(R.layout.dialog_list);
dialog.setTitle("Favoriten:");
adapter = new ArrayAdapter<String>(MainSite.this, android.R.layout.simple_list_item_1, valueList);
final ListView lv = (ListView)dialog.findViewById(R.id.list_search);
lv.setAdapter(adapter);
registerForContextMenu(lv);
lv.setOnCreateContextMenuListener(new OnCreateContextMenuListener() {
public void onCreateContextMenu(ContextMenu menu, View v, ContextMenuInfo menuInfo) {
menu.add(Menu.NONE, CONTEXT_MENU_DELETE_ITEM, Menu.NONE, "Favorit entfernen");
menu.add(Menu.NONE, CONTEXT_MENU_FINISH_ITEM, Menu.NONE, "Frage abschliessen!");
}
});
lv.setChoiceMode(ListView.CHOICE_MODE_SINGLE);
lv.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View view, final int position, long id) {
String item = (String) lv.getItemAtPosition(position).toString();
Cursor c_2 = db.rawQuery("SELECT answer FROM tbl_questions"+
" where question = '"+item+"'", null);
if (c_2 != null ) {
if (c_2.moveToFirst()) {
answer = c_2.getString(c_2.getColumnIndex("answer"));
}
}
// custom dialog
final Dialog dialog = new Dialog(MainSite.this);
dialog.setContentView(R.layout.dialog_answer);
dialog.setTitle("Antwort:");
// set the custom dialog components - text, image and button
TextView text = (TextView) dialog.findViewById(R.id.txt_answer);
//text.setText(answer);
text.setText(Html.fromHtml(answer), TextView.BufferType.SPANNABLE);
Button dialogButton = (Button) dialog.findViewById(R.id.cmd_close_dialog);
// if button is clicked, close the custom dialog
dialogButton.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
dialog.dismiss();
}
});
dialog.show();
}
});
Button dialogButton = (Button) dialog.findViewById(R.id.cmd_close_dialog2);
// if button is clicked, close the custom dialog
dialogButton.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
dialog.dismiss();
}
});
dialog.show();
}
}
});
OnContextItemSelected:
#Override
public boolean onContextItemSelected(MenuItem item) {
Log.v("tst", "lol");
switch (item.getItemId()) {
case CONTEXT_MENU_DELETE_ITEM:
Log.v("DELETED", "TRUE");
return true;
case CONTEXT_MENU_FINISH_ITEM:
Log.v("FINISHED", "TRUE");
return true;
}
Log.v("FINISHED", "LOL");
return false;
}
Best Regards
MSeiz5
I found a solution here Android: ContextMenu and ItemSelected in Context Menu
public void onCreateContextMenu(ContextMenu menu, View v, ContextMenuInfo menuInfo) {
super.onCreateContextMenu(menu, v, menuInfo);
//MenuInflater inflater = getMenuInflater();
//inflater.inflate(R.menu.context_menu, menu);
MenuItem delete = menu.add("delete");
MenuItem add = menu.add("add");
add.setIcon(android.R.drawable.ic_menu_upload); //adding icons
delete.setOnMenuItemClickListener(new OnMenuItemClickListener() {
public boolean onMenuItemClick(MenuItem item) {
Log.d("ContextCheck","EDIT!");
Toast.makeText(Pr.this, "Edit!", Toast.LENGTH_SHORT).show();
return true;
}
});
add.setOnMenuItemClickListener(new OnMenuItemClickListener() {
public boolean onMenuItemClick(MenuItem item) {
Log.d("ContextCheck","EDIT!");
Toast.makeText(Pr.this, "Edit!", Toast.LENGTH_SHORT).show();
return true;
}
});
}
Is Working!
If MenuInflater used, more generic code:
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.ruleitem_menu, menu);
if (menuInfo instanceof AdapterView.AdapterContextMenuInfo){
AdapterView.AdapterContextMenuInfo adptrCmi = (AdapterContextMenuInfo) menuInfo;
String lsItem = currentRuleListView.getItemAtPosition(adptrCmi.position).toString();
menu.setHeaderTitle( lsItem);
}
//if Activity.onContextItemSelected not triggered, try the following lines
for (int i=0; i< menu.size();i++){
menu.getItem(i).setOnMenuItemClickListener(new OnMenuItemClickListener(){
#Override
public boolean onMenuItemClick(MenuItem item) {
return onContextItemSelected(item);
}
});
}
Related
I'm new in Android, I have a listview of items, and I have created a popup menu, when the user press a row he must have an item in a other activity.
my problem is, he sends me always the first item... no matter where I click in the listview.
#Override
protected void onPostExecute(Boolean result) {
super.onPostExecute(result);
if (pDialog.isShowing())
pDialog.dismiss();
final ListAdapter adapter = new SimpleAdapter(busqueda.this, productos,
R.layout.list_layout, new String[]{"codigo", "descrip", "precio", "fisicolug"},
new int[]{R.id.txtCodigo, R.id.txtDescrip, R.id.txtPrecio, R.id.Stock});
lista.setAdapter(adapter);
registerForContextMenu(lista);
registerForContextMenu(textView);
}
}
#Override
public void onCreateContextMenu(ContextMenu menu, View v, ContextMenu.ContextMenuInfo menuInfo) {
MenuInflater inflate = getMenuInflater();
if (v.getId() == R.id.listView) {
inflate.inflate(R.menu.menu_main, menu);
}
}
public boolean onContextItemSelected(final MenuItem item) {
switch (item.getItemId()) {
case R.id.masIn:
TextView textView = (TextView) findViewById(R.id.txtCodigo);
String text = textView.getText().toString();
Intent intent;
intent = new Intent(getApplicationContext(), Resultado.class);
intent.putExtra("CODIGO", text);
startActivity(intent);
super.onContextItemSelected(item);
}
return true;
}
By using listview setOnItemClickListener() you can handle the click event of listview
lista.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
}
});
Im setting up a main activity with a ListView object, however, the ListView will not respond to touch, onItemClick and onContextItemSelected are not reachable, i have set up setOnItemClickListener and registerForContextMenu, and i dont see my error, here is my code:
public class MainActivity extends Activity implements OnClickListener, OnItemClickListener {
long selectedMovieId;
DbHandler dbhandler;
Movie selectedMovie;
MovieAdapter adapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button btn_setting = (Button) findViewById(R.id.page_main_setting);
Button btn_add = (Button) findViewById(R.id.page_main_add);
ListView lv = (ListView) findViewById(R.id.list);
btn_add.setOnClickListener(this);
btn_setting.setOnClickListener(this);
lv.setOnItemClickListener(this);
dbhandler = new DbHandler(this);
registerForContextMenu(lv);
Cursor c = dbhandler.queryAll();
startManagingCursor(c);
adapter = new MovieAdapter(this, c);
lv.setAdapter(adapter);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main_options, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.main_options_exit:
finish();
return true;
case R.id.main_option_delete_all:
dbhandler.deleteAll();
refresh();
return true;
}
return false;
}
#Override
public void onCreateContextMenu(ContextMenu menu, View v,
ContextMenuInfo menuInfo) {
// TODO Auto-generated method stub
getMenuInflater().inflate(R.menu.main_context, menu);
}
#Override
public boolean onContextItemSelected(MenuItem item) {
Log.d("context menu", "clicked");
AdapterContextMenuInfo info = (AdapterContextMenuInfo) item.getMenuInfo();
selectedMovieId = info.id;
switch (item.getItemId()) {
case R.id.main_context_edit:
Intent intent = new Intent(this, AddEditActivity.class);
intent.putExtra(DbConstants.FROM_CONTEXT, selectedMovie+"");
startActivity(intent);
return true;
case R.id.main_context_delete:
dbhandler.deleteMovie(selectedMovieId);
refresh();
return true;
}
return false;
}
#Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.page_main_setting:
openOptionsMenu();
break;
case R.id.page_main_add:
DialogInterface.OnClickListener listenerInternet = new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
Intent intent = new Intent(getBaseContext(),
InternetEditActivity.class);
startActivity(intent);
}
};
DialogInterface.OnClickListener listenerManual = new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
Intent intent = new Intent(getBaseContext(),AddEditActivity.class);
intent.putExtra(DbConstants.MANUAL, DbConstants.MANUAL);
startActivity(intent);
}
};
AlertDialog dialog = new AlertDialog.Builder(this)
.setTitle("Please choose an adding method")
.setCancelable(false).setNegativeButton("Cancel", null)
.setNeutralButton("via internet", listenerInternet)
.setPositiveButton("Manual", listenerManual).create();
dialog.show();
break;
}
}
class MovieAdapter extends CursorAdapter /*implements OnTouchListener*/ {
public MovieAdapter(Context context, Cursor c) {
super(context, c);
}
#Override
public View newView(Context context, Cursor cursor, ViewGroup parent) {
// inflate the view:
return getLayoutInflater().inflate(R.layout.main_list_layout,
parent, false);
}
#Override
public void bindView(View view, Context context, Cursor cursor) {
// bind the data
// get the data from the cursor
String subject = cursor.getString(cursor.getColumnIndex(DbConstants.DB_SUBJECT));
String body = cursor.getString(cursor.getColumnIndex(DbConstants.DB_BODY));
String internal_location = cursor.getString(cursor.getColumnIndex(DbConstants.DB_INTERNAL_LOCATION));
int year = cursor.getInt(cursor.getColumnIndex(DbConstants.DB_YEAR));
int status = cursor.getInt(cursor.getColumnIndex(DbConstants.DB_STATUS));
int rating = cursor.getInt(cursor.getColumnIndex(DbConstants.DB_RATING));
TextView subjectText = (TextView) view.findViewById(R.id.list_main_subject);
TextView bodyText = (TextView) view.findViewById(R.id.list_main_body);
TextView yearText = (TextView) view.findViewById(R.id.list_main_year);
TextView statusText = (TextView) view.findViewById(R.id.list_main_status);
ImageView image = (ImageView) view.findViewById(R.id.list_main_imgae);
//RatingBar ratingBar = (RatingBar) view.findViewById(R.id.list_main_ratingBar1);
//ratingBar.setOnTouchListener(this);
subjectText.setText(subject);
bodyText.setText(body);
yearText.setText(String.valueOf(year));
//ratingBar.setRating(rating);
Log.d("status in main", status+"");
Log.d("rating in main", rating+"");
if (status==0){
statusText.setText("watched");
} else if (status==1){
statusText.setText("Not watched");
}
Log.d("ternal loction", internal_location+"!");
if (internal_location!=null){
File imgFile = new File(internal_location);
if(imgFile.exists()){
Bitmap myBitmap = BitmapFactory.decodeFile(imgFile.getAbsolutePath());
image.setImageBitmap(myBitmap);
}
}
}
/*#Override
public boolean onTouch(View v, MotionEvent event) {
return true;
}*/
} //Movie Adapter close
public void refresh(){
Cursor newCursor = dbhandler.queryAll();
Cursor oldCursor = adapter.getCursor();
adapter.changeCursor(newCursor);
startManagingCursor(newCursor);
stopManagingCursor(oldCursor);
oldCursor.close();
}
#Override
public void onItemClick(AdapterView<?> arg0, View v, int arg2, long id) {
Log.d("list menu", "clicked");
Intent intent = new Intent(this, AddEditActivity.class);
intent.putExtra(DbConstants.FROM_LISTVIEW, id);
startActivity(intent);
}
} //Main Activity close
it has to be somthing to do with the layout of the list, a simple list inserted next to it worked
OnItemClick event is now intercepted by RatingBar.
Add onTouchEvent listener to your RatingBar and return false to say to system that RatingBar does not handle this events.
#Override
public boolean onTouchEvent(MotionEvent event) {
super.onTouchEvent(MotionEvent event)
return false;
}
Edit: above answer is for subclassing RatingBar.
But you already have onTouchEvent just return false instead of true.
The problem was that there was a Scroll view object in the layout of the adapter, remove it and the problem will be fixed
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 would like some guidance on how to create a clickable Listview and go to new page where the user can add items within the list as I am creating a To Do List, and I want the user to be able to create multiple lists, and then tap the list, and enter multiple items within that very list.
Thanks.
UPDATE - Added .java code for reference. This may explain what I have implemented thus far better than the text above.
public class ActionBarMenuDemoActivity extends SherlockListActivity {
private static final String[] items = { };
private ArrayList<String> words = null;
#Override
public void onCreate(Bundle icicle) {
super.onCreate(icicle);
initAdapter();
registerForContextMenu(getListView());
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
new MenuInflater(this).inflate(R.menu.option, menu);
EditText add = null;
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
View v = menu.findItem(R.id.add).getActionView();
if (v != null) {
add = (EditText) v.findViewById(R.id.title);
}
}
if (add != null) {
add.setOnEditorActionListener(onSearch);
}
return (super.onCreateOptionsMenu(menu));
}
public void onCreateContextMenu(Menu menu, View v,
ContextMenu.ContextMenuInfo menuInfo) {
new MenuInflater(this).inflate(R.menu.context, menu);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch(item.getItemId())
{
case R.id.add:
add();
break;
case R.id.preferences:
startActivity(new Intent(getApplicationContext(),SettingsActivity.class));
break;
}
return (super.onOptionsItemSelected(item));
}
#Override
#SuppressWarnings("unchecked")
public boolean onContextItemSelected(android.view.MenuItem item) {
AdapterView.AdapterContextMenuInfo info = (AdapterView.AdapterContextMenuInfo) item.getMenuInfo();
ArrayAdapter<String> adapter = (ArrayAdapter<String>) getListAdapter();
int itemId = item.getItemId();
if (itemId == R.id.cap) {
String input = words.get(info.position);
input = input.toUpperCase();
adapter.remove(words.get(info.position));
adapter.insert(input, info.position);
return (true);
}
return (super.onContextItemSelected(item));
}
private void initAdapter() {
words = new ArrayList<String>();
for (String s : items) {
words.add(s);
}
setListAdapter(new ArrayAdapter<String>(this,
android.R.layout.simple_list_item_1, words));
}
private void add() {
final View addView = getLayoutInflater().inflate(R.layout.add, null);
new AlertDialog.Builder(this).setTitle("Add a List").setView(addView)
.setPositiveButton("Create", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
addWord((TextView) addView.findViewById(R.id.title));
}
}).setNegativeButton("Cancel", null).show();
}
#SuppressWarnings("unchecked")
private void addWord(TextView title) {
ArrayAdapter<String> adapter = (ArrayAdapter<String>) getListAdapter();
adapter.add(title.getText().toString());
Toast.makeText(ActionBarMenuDemoActivity.this,
title.getText().toString() + " Created", Toast.LENGTH_LONG)
.show();
title.setText("");
}
private TextView.OnEditorActionListener onSearch = new TextView.OnEditorActionListener() {
public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
if (event == null || event.getAction() == KeyEvent.ACTION_UP) {
addWord(v);
InputMethodManager imm = (InputMethodManager) getSystemService(INPUT_METHOD_SERVICE);
imm.hideSoftInputFromWindow(v.getWindowToken(), 0);
}
return (true);
}
};
}
Some of this code will be removed, as I used a tutorial as my starting point.
I have a dialog that shows a list of items, I need to be able to edit/delete items in this list so I put a context menu in so when the user long presses on an item it they can choose what they want to do (edit or delete the item).
The problem is that onContextItemSelected never gets called when an item in the context menu is selected.
I checked to see if maybe the activity that created the dialog fragment is getting the callback but that is not either so why is there it not getting called? Can you not do a context menu in a dialog?
public class TypesDialogList extends DialogFragment implements LoaderManager.LoaderCallbacks<Cursor>,OnItemClickListener,OnCreateContextMenuListener{
ListView lv;
SimpleCursorAdapter mAdapter;
private int EDIT_TYPE = 1;
private int DELETE_TYPE = 2;
OnEditType mType;
public Dialog onCreateDialog(Bundle state){
final View v = getActivity().getLayoutInflater().inflate(R.layout.layer_dialog_layout, null, false);
lv = (ListView)v.findViewById(R.id.listView1);
lv.setChoiceMode(ListView.CHOICE_MODE_SINGLE);
lv.setOnItemClickListener(this);
lv.setOnCreateContextMenuListener(this);
return new AlertDialog.Builder(getActivity()).setView(v).setPositiveButton("Add Type", new OnClickListener(){
public void onClick(DialogInterface dialog, int which) {
}
}).setTitle("Type's").create();
}
#Override
public void onCreateContextMenu(ContextMenu menu, View v, ContextMenu.ContextMenuInfo menuInfo){
super.onCreateContextMenu(menu, v, menuInfo);
AdapterView.AdapterContextMenuInfo info = (AdapterView.AdapterContextMenuInfo) menuInfo;
long id = info.id;
if(id > 3){
menu.setHeaderTitle("Type Menu");
menu.add(Menu.NONE, EDIT_TYPE, 1, "Edit");
menu.add(Menu.NONE, DELETE_TYPE, 2, "Delete");
}else{
Toast.makeText(getActivity(),"Cannot edit type",Toast.LENGTH_SHORT).show();
}
}
#Override
public boolean onContextItemSelected(MenuItem item) {
super.onContextItemSelected(item);
AdapterView.AdapterContextMenuInfo oMenuInfo = (AdapterView.AdapterContextMenuInfo) item.getMenuInfo();
long id = oMenuInfo.id;
if(item.getItemId() == EDIT_TYPE){
}else if(item.getItemId() == DELETE_TYPE){
}
return true;
}
}
For anybody still looking for a workaround, I just solved this problem by creating an anonymous OnMenuItemClickListener that delegates back to onContextItemSelected(MenuItem item) and setting it on all the items in my menu.
#Override
public void onCreateContextMenu(ContextMenu menu, View view, ContextMenuInfo menuInfo) {
// Creation/inflate menu here
OnMenuItemClickListener listener = new OnMenuItemClickListener() {
#Override
public boolean onMenuItemClick(MenuItem item) {
onContextItemSelected(item);
return true;
}
};
for (int i = 0, n = menu.size(); i < n; i++)
menu.getItem(i).setOnMenuItemClickListener(listener);
}