在Android的其他view元素之间插入/移除view元素



如何在View元素之间添加TextView/Button

我正在从服务器获取评论和它的回复,如果评论有回复,那么它将显示查看回复按钮,当用户触摸按钮时,它将为该评论获取回复,并仅在该评论下方显示。,当用户再次按下回复按钮时,回复将消失

<ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:fillViewport="true"
            android:orientation="vertical" >
                    <LinearLayout
                    android:layout_width="fill_parent"
                    android:layout_height="wrap_content"
                    android:orientation="vertical"
                    android:id="@+id/commentScrollLayout"
                    >

                   </LinearLayout>
            </ScrollView>

获取的评论添加在LinearLayout- id-commentScrollLayout,所以我的问题是我如何插入/删除回复的评论?

您可以在LinearLayout上使用addView方法。此方法接受第二个参数-要插入视图的位置的索引。现在需要根据按下的注释确定该索引。你可以使用indexOfChild方法:

View pressedComment; // Comment pressed by user.
LinearLayout comments = (LinearLayout) findViewById(R.id.commentScrollLayout); 
// Get index of pressed comment.
int index = comments.indexOfChild(pressedComment);
// Create reply text view.
TextView reply = ..;
// Insert reply after the comment.
comments.addView(reply, index + 1);

对于删除,您可以通过索引删除回复,或者如果您在某处保存了视图,则可以通过视图删除回复。查看removeView和removeViewAt

您可以使用这两个命令删除和添加视图。

View.removeView();
View.addView();

通过调用

获取视图
findViewById(R.id.yourviewid);

创建视图:

TextView tv = new TextView(this);

添加视图

LinearLayout ll = (LinearLayout) findViewByid(R.id.commentScrollLayout);
TextView tv = new TextView(this);
tv.setId(1337);
tv.setText("Test");
ll.addView(tv);

删除视图

LinearLayout ll = (LinearLayout) findViewByid(R.id.commentScrollLayout);
TextView tv = (TextView) findViewByid(1337);
ll.removeView(tv);

使TextView全局,你不需要id。

最新更新