Android I';在片段中创建线性布局。如何从活动中动态添加视图?
我正在发布一个片段中的数据,并通过添加一个视图来更新另一个片段。我没有使用listView。我正在使用LinearLayout 我有一个很简单的疑问。如何获取视图并通过向其添加另一个视图进行更新 基本上,我想扩大已有数据的linearlayout,并在添加片段的主活动中为其添加一个视图 编辑:Android I';在片段中创建线性布局。如何从活动中动态添加视图?,android,Android,我正在发布一个片段中的数据,并通过添加一个视图来更新另一个片段。我没有使用listView。我正在使用LinearLayout 我有一个很简单的疑问。如何获取视图并通过向其添加另一个视图进行更新 基本上,我想扩大已有数据的linearlayout,并在添加片段的主活动中为其添加一个视图 编辑: LinearLayout ll = (LinearLayout)fragment.getView().findViewById(R.id.commentFragmentLayout);
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()。问题是,如果调用remove view,则会丢失以前插入到布局中的数据 你发布的代码毫无意义。从片段中获取id为
R.id.commentFragment
的LinearLayout
的父对象,在该父对象中搜索TextView
以设置一些文本,然后将父对象添加到自身
我有一个很简单的疑问。如何获取视图并通过
为它添加另一个视图
您可以使用getView()
获得片段的视图。在getView()
返回的视图中搜索所需组件,然后将所需视图添加到该容器中:
LinearLayout ll = (LinearLayout)fragment.getView().findViewById(R.id.commentFragmentLayout);
TextView newText = new TextView(context);
newText.setText("Important text");
ll.addView(newText);
基本上,我想膨胀已经有数据的线性布局
并在添加片段的主活动中向其添加视图
充气的布局文件不是已存在的视图。我真的不明白您想在这里解释什么。请尝试更好地解释。使用getViewById获得所需的视图。然后您可以将其他视图添加到其中。您不能从该布局添加TextView,因为它已添加到视图层次结构中。而是添加膨胀的布局子级:ll.addView(子级)代码>。
LayoutParams params =new LinearLayout.LayoutParams(LayoutParams.FILL_PARENT,LayoutParams.WRAP_CONTENT);
LinearLayout layout = new LinearLayout(this);
layout.setOrientation(LinearLayout.VERTICAL);
lay=(LinearLayout)rootView.findViewById(R.id.Lay);
lay.addView(yourView);