Java 在linearlayout中以编程方式编辑视图

Java 在linearlayout中以编程方式编辑视图,java,android,view,android-linearlayout,Java,Android,View,Android Linearlayout,这是我的布局xml文件: <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical" > <LinearLayout andr

这是我的布局xml文件:

<LinearLayout 
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical" >

    <LinearLayout 
        android:id="@+id/container1"       
        android:tag="1"
        //... >

        <TextView
            android:id="@+id/txt1"
            android:tag="1"
            //... />

    </LinearLayout>

    <LinearLayout 
        android:id="@+id/container2"
        android:tag="2"
        //... >

        <TextView
            android:id="@+id/txt2"
            android:tag="2"
            //... />
    </LinearLayout>

    //...
-

但这就是我在日志上看到的:

java.lang.IllegalStateException: The specified child already has a parent. You must call removeView() on the child's parent first.

您必须在运行时在linearlayout中添加textview,而不是在编译时在xml中添加textview


如果在运行时添加textview,则不会出现错误

linearLayout.removeAllViews();

final TextView person1 = new TextView(this);
linearLayout1.addView(person1);

final TextView person2 = new TextView(this);
linearLayout2.addView(person2);

您必须在运行时在linearlayout中添加textview,而不是在编译时在xml中添加textview


如果在运行时添加textview,则不会出现错误

linearLayout.removeAllViews();

final TextView person1 = new TextView(this);
linearLayout1.addView(person1);

final TextView person2 = new TextView(this);
linearLayout2.addView(person2);

两种布局都包含一个
TextView
。因此,与其删除和添加视图,不如在它们之间切换文本?这将节省您的时间,您的性能也会更好。

两个版面都包含一个
TextView
。因此,与其删除和添加视图,不如在它们之间切换文本?这将节省您的时间,您的表现也会更好。

@BhaveshJethani谢谢!嗯,我要说的是,我真正做的是使用拖放将一个textview移动到另一个版面,所以我要做的是尝试找到将另一个textview移动到第一个版面的方法,这就是exchange booth。因此,改变他们的名字并不是一件容易的事option@masmic_87实现您的拖放功能,当您获得用户拖放的事件时,只需切换文本,效果似乎是一样的。如果这不是一个选项,那么你可以使用Bhavesh的建议。我将尝试你所说的,简化EditText,这里只显示id和标记,但在我的布局中有多个参数,所以在必须按语法声明所有参数之前,我将为你的answer@BhaveshJethani谢谢嗯,我要说的是,我真正做的是使用拖放将一个textview移动到另一个版面,所以我要做的是尝试找到将另一个textview移动到第一个版面的方法,这就是exchange booth。因此,改变他们的名字并不是一件容易的事option@masmic_87实现您的拖放功能,当您获得用户拖放的事件时,只需切换文本,效果似乎是一样的。如果这不是一个选项,那么你可以使用Bhavesh的建议。我将尝试你所说的,为了简化编辑文本,这里只显示id和标记,但在我的布局中,有多个参数,所以在必须按语法声明所有参数之前,我将对你的答案进行排序
LinearLayout ll = (LinearLayout) findViewById(R.id.your_ll_id);
TextView tv = (LinearLayout) findViewById(R.id.your_tv_id);
ViewGroup parent = (ViewGroup) tv.getParent();
parent.removeView(tv);
tv.setLayoutParams(new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT));
//...
ll.addView(tv);
linearLayout.removeAllViews();

final TextView person1 = new TextView(this);
linearLayout1.addView(person1);

final TextView person2 = new TextView(this);
linearLayout2.addView(person2);