在一个片段中我有一个线性布局。如何从活动中动态地向其添加视图?

3

我正在从一个片段中发布数据,并通过向其添加视图来更新另一个片段。我没有使用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,我会丢失之前在布局中插入的数据。

使用 getViewById 获取所需的视图,然后您可以将其他视图添加到其中。 - bhups
3个回答

1

你发布的代码没有任何意义。你从片段中获取具有id R.id.commentFragmentLinearLayout的父级,在该父级中搜索TextView以设置一些文本,然后将父级添加到自身。

我有一个非常简单的疑问。如何获取视图并通过添加另一个视图来更新它?

你可以使用getView()获取片段的View。在由getView()返回的视图上搜索所需的组件,然后将所需的视图添加到该容器中:

LinearLayout ll = (LinearLayout)fragment.getView().findViewById(R.id.commentFragmentLayout);
TextView newText = new TextView(context);
newText.setText("Important text");
ll.addView(newText);

基本上,我想要扩展已经有数据的LinearLayout,并在添加片段的主活动中向其添加视图。
您应该扩展布局文件而不是已经存在的视图。我真的不理解您想要什么,请尽量解释清楚。

你不能将TextView从该布局中添加,因为它已经被添加到视图层次结构中。相反,添加充气的布局child: ll.addView(child); - user

0
 LayoutParams params =new LinearLayout.LayoutParams(LayoutParams.FILL_PARENT,LayoutParams.WRAP_CONTENT);
        LinearLayout layout = new LinearLayout(this);
        layout.setOrientation(LinearLayout.VERTICAL);

0
 lay=(LinearLayout)rootView.findViewById(R.id.Lay);
 lay.addView(yourView);

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接