我有一个动态添加行的TableLayout。在每行中有2个元素,其中一个是TextView,另一个是Button。当我单击行中存在的按钮时,该行应该被删除如何在Android中完成?如何查找rowid以及如何动态删除行。 任何人都可以帮我解决这个问题。
先谢谢,
答案 0 :(得分:0)
尝试这种方法:
TableRow tableRow;
TextView tv;
Button button;
//...
tableRow.addView(tv)
tableRow.addView(button);
//somewhere where you want to delete
ViewGroup parent=button.getParent();
if(parent instanceof TableRow)
//do deleting task
答案 1 :(得分:0)
试试这个:
public void onClick(View v) {
// TODO Auto-generated method stub
TableRow t = (TableRow) v.getParent();
TextView firstTextView = (TextView) t.getChildAt(0);
code = firstTextView.getText().toString();
System.out.println("code>>>>>>" + code);
View row = (View) v.getParent();
// container contains all the rows, you could keep a
// variable somewhere else to the container which you
// can refer to here
ViewGroup container = ((ViewGroup) row.getParent());
// delete the row and invalidate your view so it gets
// redrawn
container.removeView(row);
container.invalidate();
}
答案 2 :(得分:0)
添加行时,您可以指定标签或ID。然后只需使用该标记/ id删除该行。
TableLayout table; // global access, probably initialized in onCreate()
// initialization, etc.
创建将添加到TableLayout的元素,使用TextView和Button的TableRow然后在将其添加到TableLayout之前调用addDeleteClick(yourButton, uniqueTag)
。
// example of adding a text view and a button the the TableLayout
void addToTableLayout(String text, String uniqueTag) {
TableRow tr = new TableRow(yourActivity);
// set the unique tag that will be used when deleting this row
tr.setTag(uniqueTag);
// do what you need with the button and textview
TextView tv = new TextView(yourActivity);
tv.setText(text);
Button bt = new Button(yourActivity);
// add delete click capability to the button
addDeleteClick(bt, uniqueTag);
table.addView(tr, new TableLayout.LayoutParams(
LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT));
}
// Adds the delete on click capability to a button
// to delete a row from TableLayout based on its tag
void addDeleteClick(Button bt, final String tag) {
bt.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View arg0) {
Log.d("TableLayout", " deleting row with tag " + tag);
deleteRow(tag);
}
});
}
// delete a row from TableLayout based on its tag
void deleteRow(String tag) {
View removedRow = table.findViewWithTag(tag);
table.removeView(removedRow);
table.invalidate();
}