How can I set title of the context menu from the selected Listview item? This below is my main activity.
public class OListActivity extends ListActivity {
......
......
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
registerForContextMenu(getListView());
......
......
MatrixCursor cursor;
cursor = NameManager.getnameList();
startManagingCursor(cursor);
String[] from = { "name", "info", "status", BaseColumns._ID };
int[] to = { R.id.name, R.id.info, R.id.status };
SimpleCursorAdapter adapter = new SimpleCursorAdapter(this,
R.layout.row, cursor, from, to);
setListAdapter(adapter);
}
#Override
public void onCreateContextMenu(ContextMenu menu, View v,
ContextMenuInfo menuInfo) {
super.onCreateContextMenu(menu, v, menuInfo);
menu.setHeaderTitle("Menu");// TODO Change to name of selected listview item.
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.context_menu, menu);
}
.....
.....
I need to set menu.setHeaderTitle to R.id.name. I'm aware of another similer question but it don't mention about dealing with a complex ListView with multiple textviews.
Use the ContextMenuInfo parameter from the onCreateContextMenu() method:
#Override
public void onCreateContextMenu(ContextMenu menu, View v,
ContextMenuInfo menuInfo) {
super.onCreateContextMenu(menu, v, menuInfo);
AdapterView.AdapterContextMenuInfo info;
try {
// Casts the incoming data object into the type for AdapterView objects.
info = (AdapterView.AdapterContextMenuInfo) menuInfo;
} catch (ClassCastException e) {
// If the menu object can't be cast, logs an error.
Log.e(TAG, "bad menuInfo", e);
return;
}
Cursor cursor = (Cursor) getListAdapter().getItem(info.position);
if (cursor == null) {
// For some reason the requested item isn't available, do nothing
return;
}
// if your column name is "name"
menu.setHeaderTitle(cursor.getString(cursor.getColumnIndex("name")));
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.context_menu, menu);
}
I know this is quite an old post and is the correct answer as well. However, while using this today I came across something I will like to add.
The ContextMenuInfo parameter is used to find the exact item position which initiated the ContextMenu i.e our adpater item.
Hence, it can return an item of type defined in the Adapter's getItem() method using that position info.position, as in the above the getItem() method returns a Cursor object.
(In my case it returned a Model class and then I realized that to set the Title via menu.setHeaderTitle() I can pass my methods that my model supports like model.getItamName())
Also, remember if your AdapterView contains any header you will have to exclude them while fetching the position using menuInfo. Like,
Cursor cursor = (Cursor) getListAdapter().getItem(info.position - yourList.getHeaderViewsCount());
Hope this helps someone. :)
Related
I have populated listview from database using ArrayAdapter, i want to get the database-row id of the list item when i click the the item. I have searched many hours, but i couldn't get the answer because i am beginner.
here is my main.java
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ListView listView=findViewById(R.id.quote_list);
registerForContextMenu(listView);
DatabaseAccess datac= DatabaseAccess.getInstance(getApplicationContext());
datac.open();
final ArrayList<String> thelist = new ArrayList<>();
Cursor data=datac.getquotes();
while(data.moveToNext()){
thelist.add(data.getString(2));
ListAdapter listAdapter = new ArrayAdapter<>(this,R.layout.textcenter,R.id.textitem,thelist);
listView.setAdapter(listAdapter);
}
}
#Override
public void onCreateContextMenu(ContextMenu menu, View v, ContextMenu.ContextMenuInfo menuInfo) {
super.onCreateContextMenu(menu, v, menuInfo);
MenuInflater menuInflater=getMenuInflater();
menuInflater.inflate(R.menu.my_contextual_menu,menu);
}
#Override
public boolean onContextItemSelected(MenuItem item) {
AdapterView.AdapterContextMenuInfo info =(AdapterView.AdapterContextMenuInfo)item.getMenuInfo();
return super.onContextItemSelected(item);
}
}
Try in this way,
1. When you click on the item of list view, you will get the id.
2. get the string value from that index and call a method where send collected string as a parameter and fire a query in that method like
return db.rawQuery("select row_id from your_tableName where string_columnName="+your_passed_string+";",null);
Collect row_id in your cursor and convert it into a int value then show it on screen.
Done.
I need to change list of menu items(actually hide one or just make it not clickable) depending on list item long-clicks.
I asume I can do it somehow in setOnItemLongClickListener but can't find solution:
public void onCreate(Bundle savedInstanceState){
......
registerForContextMenu(listView);
listView.setOnItemLongClickListener(new OnItemLongClickListener() {
#Override
public boolean onItemLongClick(AdapterView<?> adapterView , View v,int position, long id) {
MyListItem item = (MyListItem) listView.getItemAtPosition(position);
listView.showContextMenu();
return true;
}
});
Just found only solution with global variable to set value in OnItemLongClickListener depend on item clicked values and check it in onCreateContextMenu. Also can save there just clicked item (MyListItem). But I think exists more elegant solution.
public void onCreateContextMenu(ContextMenu menu, View v, ContextMenuInfo menuInfo) {
super.onCreateContextMenu(menu, v, menuInfo);
if(!someGlobalVar){
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.list_item, menu);
}
...
or
if(!someGlobalVar){
menu.getItem(0).setVisible(someGlobalVar);
}
}
I have a simple layout where there are few textviews. Here what I do is define a name, and save it into a database using a contentProvider. Then, this name is read from the database and shown on the textView.
This is how I first get the item saved on the database:
Cursor c = getContentResolver().query(TravelersProvider.CONTENT_URI, PROJECTION, null, null, null);
The projection is:
String[] PROJECTION = {Travelers._ID, Travelers.NAME};
Now What I need to do is:
Create contextMenu for when I click on the textview with the name, I can edit or delete it.
This is the way I register the contextMenu to the TextView:
txtView1.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
registerForContextMenu(v);
}
});
Then I create it:
#Override
public void onCreateContextMenu(ContextMenu menu, View v, ContextMenuInfo menuInfo) {
super.onCreateContextMenu(menu, v, menuInfo);
getMenuInflater().inflate(R.menu.context_menu, menu);
}
And finally I define what to do when touching:
#Override
public boolean onContextItemSelected(MenuItem item) {
//TODO:
}
Here is where I need some help. Basically, what I need to do is:
Define wich element is the one that I've touched. This should obtain an index.
Get the cursor and move it to that position.
In the onCreateContextMenu hook, there is a View parameter. Call getId() on this parameter to determine which TextView invoked the context menu. Then you can store this into a class variable to be used in onContextItemSelected.
private int contextViewId;
#Override
public void onCreateContextMenu(ContextMenu menu, View v, ContextMenuInfo menuInfo) {
super.onCreateContextMenu(menu, v, menuInfo);
getMenuInflater().inflate(R.menu.context_menu, menu);
contextViewId = v.getId();
}
#Override
public boolean onContextItemSelected(MenuItem item) {
// use contextViewId
}
I am building a custom ListView (card style) and would like to have an edit and delete button on the card. In order to invoke the methods on the correct database rows, I need to know which _id (View) the user selected.
Currently, I am using a context menu which is pretty easy
#Override
public void onCreateContextMenu(ContextMenu menu, View v,
ContextMenuInfo menuInfo) {
super.onCreateContextMenu(menu, v, menuInfo);
AdapterContextMenuInfo info = (AdapterContextMenuInfo) menuInfo;
position = (int) info.id;
MenuInflater m = getMenuInflater();
m.inflate(R.menu.history_popup_menu, menu);
}
#Override
public boolean onContextItemSelected(final MenuItem item) {
switch(item.getItemId()){
case R.id.delete:
...
in this case, I get the id (position) in the onCreateContextMenu
I am wanting to get rid of the context menu now and just have edit and delete on the card itself.
How do I go about retrieving the _id from the database and assign it to a value to be used in my delete/edit method?
This is my method for creating the list
private void addItemsToList(){
Cursor cursor = db.getAllLogs();
Log.d("history.java", "finished Cursor cursor = db.getAllLogs();");
String[] from = {"_id", "date", "gallons", "pricePerGallon", "odometer", "filledOrNot", "comments", "totalSpent"};
int[] to = {deleteVal, R.id.cardDate, R.id.cardGallons, R.id.cardPrice, R.id.cardOdometer, R.id.cardFilledOrNot, R.id.cardComments, R.id.usd};
adapter = new SimpleCursorAdapter(this, R.layout.history_list_item, cursor, from, to, 0);
String filledOrNotVal = String.valueOf(R.id.cardFilledOrNot);
if (filledOrNotVal == "False"){
Log.d("history", "False");
} else {
Log.d("history", "True");
}
listContent.setAdapter(adapter);
}
I'm doing a proyect where i have a view with multiple listview created at runtime, every listview load specifics rows of a database. and i want to implement a contextmenu. The problem is how can i get the row of the listview to retieve the id of the database? How can i get my list adapter inside the contextmenu ? or some other solution. Thanks!
here is a part of the code...
private void makeView(){
yearsArray = db.getUniqueYears(TABLE_NAME);
for (int i = 0; i < yearsArray.size() ; i++){
list = db.getDocByYear(TABLE_NAME, yearsArray.get(i));
custom_adapter = new Document_adapter(this, list);
ListView lv = new ListView(this);
lv.setAdapter(custom_adapter);
lv.setBackgroundResource(R.drawable.title_container_bg);
registerForContextMenu(lv);
}
}
#Override
public void onCreateContextMenu(ContextMenu menu, View v,
ContextMenuInfo menuInfo) {
super.onCreateContextMenu(menu, v, menuInfo);
MenuInflater mi = getMenuInflater();
mi.inflate(R.menu.doc_options, menu);
}
#Override
public boolean onContextItemSelected(MenuItem item) {
AdapterContextMenuInfo info = (AdapterContextMenuInfo) item.getMenuInfo();
/*
*/
return super.onContextItemSelected(item);
}
If you set your database up properly you can just do this info.id; in your onContextItemSelected and that gives the database id