我将根据点击的内容从android中的TableLayout中删除TableRow。此表布局从SQLiteDatabase填充。我试图设置单击行的ID并删除单击的行。它仅工作一次,当我第二次单击删除按钮删除更多行时,应用程序停止。
我认为这是因为当我删除第二行(即ID为2)时,第一行ID为3,第二行在删除第二行时变为2。 知道如何从TableLayout中删除选定的行??
这是删除行的方法:
btnRemove.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
try {
int rowIDs = tampRowID;
int SOUDetailNo = tampRowID + LastSOUDetail;
mytable.removeViewAt(tampRowID);
b.deleteSOUD(SOUDetailNo);
Toast.makeText(Order.this, "SOUploadDetail no "+ Integer.toString(SOUDetailNo) + " has been deleted", Toast.LENGTH_SHORT).show();
} catch (NumberFormatException e) {
// TODO: handle exception
Toast.makeText(Order.this, "could not parse", Toast.LENGTH_SHORT).show();
}
}
});
}
我在BuildTable()方法中设置了行ID:
private void BuildTable()
{
int rowID = 0;
Cursor c = b.readAllSOUD();
final int rows = c.getCount();
int cols = c.getColumnCount();
c.moveToPosition(c.getCount() - 1);
// outer for loop
final TableRow row = new TableRow(this);
row.setLayoutParams(new LayoutParams(LayoutParams.WRAP_CONTENT,LayoutParams.WRAP_CONTENT));
row.setClickable(true);
rowID++;
row.setId(rowID);
row.setBackgroundColor(Color.WHITE);
row.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
tampRowID = row.getId();
}
});
// inner for loop
for (int j = 0; j < cols; j++)
{
TextView tv = new TextView(this);
tv.setLayoutParams(new LayoutParams(LayoutParams.WRAP_CONTENT,
LayoutParams.WRAP_CONTENT));
//tv.setBackgroundResource(R.drawable.cell_shape);
tv.setGravity(Gravity.LEFT);
tv.setTextSize(12);
tv.setPadding(0, 5, 0, 5);
tv.setText(c.getString(j));
//tv.setBackgroundColor(0x7C5B77);
row.addView(tv);
}
c.moveToNext();
mytable.addView(row);
}
答案 0 :(得分:0)
您可以尝试以下答案。
public TableLayout mainTableLayout;
private TableRow tableRow;
mainTableLayout = (TableLayout) findViewById(R.id.mainTable);
//when you click row item on the table show Menu dialog
@Override
public void onCreateContextMenu(ContextMenu menu, View v,
ContextMenuInfo menuInfo) {
super.onCreateContextMenu(menu, v, menuInfo);
if (((TableLayout) v.getParent()).getId() == mainTableLayout
.getId()) {
menu.setHeaderTitle("Options");
menu.add(0, v.getId(), 0, "Delete");
} else {
menu.setHeaderTitle("Options");
menu.add(0, v.getId(), 0, "Delete");
}
tableRow = (TableRow) v;
}
@Override
public boolean onContextItemSelected(MenuItem item) {
if (item.getTitle() == "Delete") {
deleteFunction(item.getItemId());
} else {
return false;
}
return true;
}
public void deleteFunction(int id) {
if (((TableLayout) tableRow.getParent()).equals(mainTableLayout)) {
mainTableLayout.removeView(tableRow);
try {
//what want something to do on the table column eg. for update column.
} catch (NullPointerException e) {
e.printStackTrace();
}
} else {
}
Toast.makeText(this, "Successfully Deleted", Toast.LENGTH_SHORT).show();
}