2012-12-27 34 views
0

如何在视图元素之间添加TextView/Button。在Android中的其他视图元素之间插入/删除视图元素

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

<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添加,所以我的问题是我如何可以插入/删除回复,请对此有何评论?

回答

3

您可以在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); 

为了去除您可以通过索引或删除回复,如果你的地方保存视图,通过视图。检查removeViewremoveViewAt

+0

感谢Nikita,会被压制评论,它会评论textview编号? – SML

+0

@SunilLohar不,它将是实际的'View'代表评论。我想你可以通过'onClickListener'获取它。 –

+0

非常感谢,它工作。 – SML

0

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

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); 

OR

使TextView的全球和你不需要的ID。

相关问题