在Android中的其他视图元素之间插入/删除视图元素
如何在视图元素之间添加TextView/按钮 我正在从服务器获取评论及其回复,如果评论有回复,它将显示查看回复按钮,当用户点击按钮时,它将获取该评论的回复并仅显示在该评论下方。当用户再次按下回复按钮时,它将消失在Android中的其他视图元素之间插入/删除视图元素,android,android-layout,Android,Android Layout,如何在视图元素之间添加TextView/按钮 我正在从服务器获取评论及其回复,如果评论有回复,它将显示查看回复按钮,当用户点击按钮时,它将获取该评论的回复并仅显示在该评论下方。当用户再次按下回复按钮时,它将消失 <ScrollView xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="fill_parent" android:lay
<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上的方法。此方法采用第二个参数-要插入视图的位置索引。现在,您需要根据按下的注释确定此索引。您可以使用以下方法:
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);
对于删除,您可以按索引删除回复,如果您将视图保存在某处,则可以按视图删除回复。选中和。您可以使用这两个命令删除和添加视图
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);
或
将文本视图设置为全局,您不需要id。谢谢Nikita,将按什么注释,是否为注释文本视图id?@SunilLohar否,表示注释的将是实际的视图
。我想你可以在onClickListener
中获得它。向下投票,因为这并不能回答问题。您正在解释如何添加/删除视图,但问题是如何在其他视图之间添加视图。@zundi该问题不清楚commentScrollLayout中的布局结构。你看过我的答案了吗?因为看起来他没有使用相对论或约束论,所以我的解决方案可能是有效的,尽管我六年前的解决方案很难看。现在我建议使用RecyclerView并处理适配器内部视图的删除和添加。为此目的使用滚动视图是一个糟糕的想法。