我正在从一个片段中发布数据,并通过向其添加视图来更新另一个片段。我没有使用listView,而是使用LinearLayout。
我有一个非常简单的疑问。如何获取视图并通过向其添加另一个视图来更新它?
基本上,我想要填充已经具有数据的LinearLayout,并在添加片段的主要活动中向其添加一个视图。
编辑:
LinearLayout ll = (LinearLayout)fragment.getView().findViewById(R.id.commentFragmentLayout);
ViewGroup view = (ViewGroup) ll.getParent();
View customView = view;
TextView commentContext = (TextView) customView.findViewById(R.id.commentText);
commentContext.setText("hello");
view.addView(customView);
我尝试在主活动中执行此操作,但我的视图引发了空指针异常。
编辑2:
FragmentManager fm = getSupportFragmentManager();
// You can find Fragments just like you would with a View by using FragmentManager.
android.support.v4.app.Fragment fragment = fm.findFragmentById(R.id.fragmentCommentContent);
LayoutInflater inflater = (LayoutInflater) getApplicationContext().getSystemService(getApplicationContext().LAYOUT_INFLATER_SERVICE);
View child = inflater.inflate(R.layout.comments_list_item, null);
LinearLayout ll = (LinearLayout)fragment.getView().findViewById(R.id.commentFragmentLayout);
TextView newText = (TextView) child.findViewById(R.id.commentText);
newText.setText("Important text");
ll.addView(newText);
我尝试过这样做,得到了以下提示:指定的子元素已经有一个父级。先调用removeView()在子元素的父级上。问题是,如果我调用removeView,我会丢失之前在布局中插入的数据。