2012-12-27 80 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。

相關問題