I am creating an activity which contains one table. When selecting a row, I want to update or delete the row through context menu options. The table is within TableLayout view. Each row is added to the TableLayout as a TableRow view, and also for each TableRow I registered it for context menu with registerForContextMenu(tr);
The context menu options are displayed when selecting a row, but the problem is that I need the number of the selected row. I thought that this could be achieved with the following source code in the onContextItemSelected( MenuItem item ) method : ?
AdapterContextMenuInfo info = (AdapterContextMenuInfo) item.get开发者_运维知识库MenuInfo();
int selectedRow = (int) info.id;
but the AdapterContextMenuInfo is always null.
Could I achieve the table row by other method?
Still searching for an answer for this to see if there's a better way, but when you create your table row, you can set a tag and then retrieve it
I have this working with the onClickListener:
private void AddRow(String rowNo)
{
final TableLayout table = (TableLayout) findViewById(R.id.my_table);
final TableRow tr = (TableRow) getLayoutInflater().inflate(R.layout.table_row_item, null);
tr.setTag(rowNo);
TextView tv;
tv = (TextView) tr.findViewById(R.id.rowNo);
tv.setText(rowNo);
table.addView(tr);
tr.setOnClickListener(mClickListener);
}
Then in the OnClickListener:
private OnClickListener mClickListener = new OnClickListener()
{
public void onClick(View v)
{
try
{
String clickedRow = (String) v.getTag();
Toast toast = Toast.makeText(mContext, clickedRow, Toast.LENGTH_SHORT);
toast.show();
}
catch (Exception ex)
{
Toast toast = Toast.makeText(mContext, ex.toString(), Toast.LENGTH_SHORT);
toast.show();
}
}
};
Unless I can find another solution,, I will use the same idea for the ContextMenu
The
- public boolean onContextItemSelected(MenuItem item)
doesn't have a view parameter, but
- public void onCreateContextMenu(ContextMenu menu, View v, ContextMenuInfo menuInfo)
does,
so I guess I'll use a class level variable to store the current row in the onCreateContextMenu event and retrieve it in onContextItemSelected
精彩评论