[英]Error "The specified child already has a parent" after LinearLayout.addView() and then Linearlayout.removeView()
[英]Using addView on a View after calling removeView
我有一個要動態添加和刪除的TextView,具體取決於EditText中的文本。 我目前可以使用removeView正確地將其開始刪除,但是當我嘗試調用addView時,它會拋出NullPointerException,這可能是因為TextView一旦刪除便為null了嗎?
這是我的代碼:
final TextView tagsText = (TextView)postDialogLayout.findViewById(R.id.newPostTagsText);
//remove since start with no tags
((LinearLayout)tagsText.getParent()).removeView(tagsText);
if(currentTags.equals("Tags: <font color='#33B5E5'></font>") && tagsText.isShown())
((LinearLayout)tagsText.getParent()).removeView(tagsText);
else if(!currentTags.equals("Tags: <font color='#33B5E5'></font>") && !tagsText.isShown())
//this line below throws the NullPointerException
((LinearLayout)tagsText.getParent()).addView(tagsText);
當最后一行被調用時(我可以告訴它在正確的時間被調用),應用程序崩潰並拋出nullpointerexception。 讀取視圖的正確方法是什么?
如果要隱藏View
,則可以通過設置可見性來簡化此操作,有以下三種可能的可見性值:
View.VISIBLE
這意味着View
是可見的。 View.INVISIBLE
這意味着View
是不可見的,但仍是布局的一部分。 View.GONE
這意味着View
是不可見的,不再影響布局。 在您的情況下,將Views
可見性設置為View.VISIBLE
或View.GONE
似乎是您想要的。
您可以這樣設置可見性:
textView.setVisiblity(View.VISIBLE);
要么
textView.setVisibility(View.GONE);
您將要創建一個新的TextView,因為您已聲明了第一個TextView final。 如果您在else if語句中添加這樣的額外行,它應該可以工作:
else if (!currentTags.equals("Tags: <font color='#33B5E5'></font>") && !tagsText.isShown()) {
//this line below throws the NullPointerException
final TextView tagsText1 = (TextView)postDialogLayout.findViewById(R.id.newPostTagsText);
((LinearLayout)tagsText.getParent()).addView(tagsText1);
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.