行をTableLayout
動的に追加しました。各行には 2 つの要素があり、そのうちの 1 つはTextView
ですButton
。行にあるボタンをクリックすると、その行が削除されます。これは Android でどのように行うことができますか? 行 ID を見つける方法と、行を動的に削除する方法。誰でもこの問題を整理するのを手伝ってくれますか?
9558 次
2 に答える
7
ボタンのonClickは、クリックされたビュー、あなたの場合のボタンを提供します。そのボタンの親は、削除する行です。親からその行を削除すると、その行が削除されます。
これを実装する方法の例:
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();
}
});
于 2012-06-15T11:52:40.027 に答える
4
行を動的に追加するには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>
于 2013-01-08T09:46:29.763 に答える