在我的 android 应用程序中,我动态创建了一个 TableRow 并在此 tableRow 中插入了一个 textView 和一个 editTextView。
还有一个字段是 spinner。根据微调器上的选择创建或删除此 TableRow。
Here他们提到如何从布局中删除字段,但问题是我如何获得 View 。
我的代码是:
spinner1.setOnItemSelectedListener(new OnItemSelectedListener() {
@Override
public void onItemSelected(AdapterView<?> parent, View v,
int pos, long id) {
if (pos > 1) {
tableRowName = new TableRow(this);
tableRowName.setLayoutParams(new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT));
textViewName = new TextView(this);
textViewName.setText("Name*");
textViewName.setTextColor(Color.WHITE);
textViewName.setLayoutParams(new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT));
editTextPersonName = new EditText(this);
editTextPersonName.setHint("Name");
editTextPersonName.setLayoutParams(new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT));
tableRowName.addView(textViewName);
tableRowName.addView(editTextPersonName);
tableLayout.addView(tableRowName, new TableLayout.LayoutParams(
LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT));
} else {
tableRowName.removeView((View) v.getParent());
}
}
@Override
public void onNothingSelected(AdapterView<?> arg0) {
Toast.makeText(getApplicationContext(),
"onNothingSelected() method is called by Stage Spinner",
Toast.LENGTH_LONG).show();
}
});
此代码可以创建 tableRow 但不能删除此 tableRow。
最佳答案
您最好将 View 添加到布局 xml 中,然后动态地将可见性设置为 GONE 或 VISIBLE。
关于Android:删除动态创建的字段,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13933406/