Android:删除动态创建的字段

标签 android android-view android-spinner

在我的 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/

相关文章:

android - 为什么旋转器这么大?

android - 如何检查两个微调器的状况?

java - 从另一个 fragment : Interface of static? 添加 View 到 RecyclerView

android - 在 Android 中使用颜色选择器设置复选框颜色

Android View inflateException

android - 设置安卓 :layout_margin for a view through code

java - Android 中的微调项目

android - 使搜索栏缩略图出现在栏下方

android - 如何在列表中创建列表?

android - 获取状态栏颜色