在线性布局中以编程方式编辑视图

Posted

技术标签:

【中文标题】在线性布局中以编程方式编辑视图【英文标题】:Edit view programmatically in linearlayout 【发布时间】:2014-06-05 13:25:43 【问题描述】:

这是我的布局 xml 文件:

<LinearLayout 
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_
    android:layout_
    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>

    //...

它有 2 个容器,每个容器中有一个 textview。现在,当我触摸一个按钮时,我需要容器来交换文本视图。为此,这是我的方法:

person1 = (TextView) findViewById(R.id.txt1);
person2 = (TextView) findViewById(R.id.txt2);

place1 = (LinearLayout) findViewById(R.id.place1);
place2 = (LinearLayout) findViewById(R.id.place2);

-

place1.removeView(person1);
place2.removeView(person2);

place1.addView(person2);
place2.addView(person1);

但这就是我在 LogCat 上得到的:

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

【问题讨论】:

【参考方案1】:

两个布局都包含一个TextView。因此,您为什么不直接在它们之间切换文本,而不是删除和添加视图?这会节省你的时间,你的表现会更好。

【讨论】:

@BhaveshJethani 谢谢! 好吧,不得不说我真正在做的是使用拖放将一个文本视图移动到另一个布局,所以我正在做的是试图找到获取另一个文本视图的方法进入第一个布局,这就是,交流展位。所以改变他们的名字不是一种选择 @masmic_87 实现你的拖放功能,当你得到用户拖放的事件时,只需切换文本,效果看起来是一样的。如果这不是一个选项,那么您可以使用 Bhavesh 的建议。 我会试试你说的,为了简化这里的编辑文本,只显示 id 和标签,但在我的布局中还有几个参数,所以在必须以编程方式声明所有这些参数之前,我正在考虑你的答案【参考方案2】:
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);

【讨论】:

【参考方案3】:

你必须在运行时在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 为中心

将两个项目限制在线性布局内的顶部和底部

当以编程方式完成时,视图不会反映任何变化

在其线性布局垂直父Android中将以编程方式创建的单选按钮居中

自定义 Android 视图在线性和相对布局中显示不同