【问题标题】:I've a linear layout in a fragment. How to dynamically add a view to it from the activity?我在片段中有一个线性布局。如何从活动中动态添加视图?
【发布时间】:2012-08-25 00:45:27
【问题描述】:

我正在从一个片段发布数据并通过向另一个片段添加视图来更新另一个片段。我没有使用列表视图。我正在使用线性布局。

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

基本上我想膨胀已经有数据的线性布局,并在添加片段的主要活动中添加一个视图。

编辑:

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()。问题是,如果我调用删除视图,我会丢失之前在布局中插入的数据。

【问题讨论】:

  • 使用 getViewById 来获得想要的视图。然后你可以添加你的其他视图。

标签: android


【解决方案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);

基本上我想膨胀已经有数据的线性布局 并在添加片段的主要活动中为其添加一个视图。

你膨胀了一个布局文件而不是一个已经存在的视图。我真的不明白你想在这里尝试更好地解释。

【讨论】:

  • 您无法从该布局添加 TextView,因为它已添加到视图层次结构中。而是添加膨胀的布局child:ll.addView(child);
【解决方案2】:
 LayoutParams params =new LinearLayout.LayoutParams(LayoutParams.FILL_PARENT,LayoutParams.WRAP_CONTENT);
        LinearLayout layout = new LinearLayout(this);
        layout.setOrientation(LinearLayout.VERTICAL);

【讨论】:

    【解决方案3】:
     lay=(LinearLayout)rootView.findViewById(R.id.Lay);
     lay.addView(yourView);
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-02-29
      • 1970-01-01
      • 2019-07-12
      • 1970-01-01
      • 1970-01-01
      • 2017-01-11
      相关资源
      最近更新 更多