【问题标题】:How to remove a TextView that was added dynamically如何删除动态添加的 TextView
【发布时间】:2018-09-19 20:26:57
【问题描述】:

所以我有一个 sn-p 代码,在其中我在用户单击按钮时创建一个 textView。由于它是在运行时创建的,因此我不确定 ID 是什么。但是我想要做的是可以选择删除添加的最后一个 textView 并清除所有添加的 TextView。谢谢

private TextView createNewTextView(String text)
    {
        ArraySize++;
        final LinearLayout mLayout=findViewById(R.id.linearLayout);
        String newLine=System.getProperty("line.separator");
        final LinearLayout.LayoutParams lparams =new LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT);
        ViewGroup.LayoutParams params=(RelativeLayout.LayoutParams) mLayout.getLayoutParams();
        final TextView textView=new TextView(this);
        textView.setLayoutParams(lparams);
        textView.setText("New texT:: "+text+newLine);
        listOfNames.add(text);
        return textView;
    }

【问题讨论】:

    标签: java android textview


    【解决方案1】:

    您可以在此路径 res/values/ids.xml 中创建一个 XML 文件;

    <?xml version="1.0" encoding="utf-8"?>
    <resources>
        <item name="view_1" type="id"/>
    </resources>
    

    然后在 Java 中添加 id,像这样

    textView.setId(R.id.view_1);
    

    当你想删除它时

    LinearLayout mLayout=findViewById(R.id.linearLayout);//to find in this specific view
    TextView textView = (TextView)mLayout.findViewById(R.id.view_1);
    mLayout.removeView(textView);
    

    【讨论】:

      【解决方案2】:

      您将removeViewAt 与索引一起使用

      final LinearLayout mLayout=findViewById(R.id.linearLayout)
      mLayout.removeViewAt(mLayout.getChildCount()-1); // get the last view
      
      //or using index counter variable
      //mLayout.removeViewAt(ArraySize-1); // adjust the value accordingly
      

      或者您可以使用removeView获取视图并将其删除

      final LinearLayout mLayout=findViewById(R.id.linearLayout)
      View v = mLayout.getChildAt(mLayout.getChildCount()-1);
      mLayout.removeView(v);
      

      【讨论】:

        【解决方案3】:

        正如this问题中提到的,你可以简单地使用

        ((ViewGroup) textView.getParent()).removeView(textView);
        

        【讨论】:

          【解决方案4】:

          要删除所有视图:

          mLayout.removeAllViews();
          

          要删除最后一个 TextView:

          mLayout.removeView(mLayout.getChildAt(mLayout.getChildCount()-1));
          

          【讨论】:

            【解决方案5】:

            您可以提供一个 ID 作为 edgar 提及或使用 View.setTag ,然后您可以使用 viewGroup.findViewWithTag 按标签查找视图。

            【讨论】:

              猜你喜欢
              • 1970-01-01
              • 1970-01-01
              • 2017-09-13
              • 1970-01-01
              • 1970-01-01
              • 1970-01-01
              • 1970-01-01
              • 1970-01-01
              • 1970-01-01
              相关资源
              最近更新 更多