[英]Delete row dynamically from table layout in android
我有一個TableLayout
,我動態添加了行。 在每一行中有2個元素,其中一個是TextView
另一個是Button
。 當我單擊一行中存在的按鈕時,應該刪除該行。 如何在Android中完成? 如何查找rowid以及如何動態刪除行。 任何人都可以幫我解決這個問題。
單擊該按鈕將為您提供單擊視圖,即您的情況下的按鈕。 該按鈕的父級是您要刪除的行。 從它的父級刪除該行將消除它。
一個如何實現這個的例子:
button.setOnClickListener(new OnClickListener()
{
@Override public void onClick(View v)
{
// row is your row, the parent of the clicked button
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();
}
});
您需要為動態添加行分配ID,並且使用它可以獲取該特定行的值,或者也可以刪除單擊行按鈕的行。
在onCreate()中: -
addButton.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
mTable.addView(addRow(mInput.getText().toString()));
}
});
private TableRow addRow(String s) {
TableRow tr = new TableRow(this);
tr.setId(1000 + sCount);
tr.setLayoutParams(new TableLayout.LayoutParams(
TableLayout.LayoutParams.FILL_PARENT,
TableLayout.LayoutParams.WRAP_CONTENT));
TableRow.LayoutParams tlparams = new TableRow.LayoutParams(
TableRow.LayoutParams.WRAP_CONTENT,
TableRow.LayoutParams.WRAP_CONTENT);
TextView textView = new TextView(this);
textView.setLayoutParams(tlparams);
textView.setText("New text: " + s);
tr.addView(textView);
TableRow.LayoutParams blparams = new TableRow.LayoutParams(
TableRow.LayoutParams.WRAP_CONTENT,
TableRow.LayoutParams.WRAP_CONTENT);
final Button button = new Button(this);
button.setLayoutParams(blparams);
button.setText(" - ");
button.setId(2000 + sCount);
button.setOnClickListener(new OnClickListener(){
@Override
public void onClick(View v) {
mTable.removeView(findViewById(v.getId() - 1000));
}
});
tr.addView(button);
sCount++;
return tr;
}
TableLayout: -
<?xml version="1.0" encoding="utf-8"?>
<ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content" >
<LinearLayout
android:id="@+id/parent"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical" >
<EditText
android:id="@+id/editText1"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
<Button
android:id="@+id/add"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
<TableLayout
android:id="@+id/table1"
android:layout_width="match_parent"
android:layout_height="wrap_content" >
</TableLayout>
</LinearLayout>
</ScrollView>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.