【问题标题】:Can't get individual references to views when inflating multiple instances膨胀多个实例时无法获得对视图的单独引用
【发布时间】:2015-01-14 20:33:18
【问题描述】:

我的意图是在 LinearLayout 上扩充同一视图的多个实例,然后相应地修改它们的视图。但是,每当我多次膨胀视图时,我总是以相同的引用结束第一个膨胀视图。

简化示例:

    View v = getActivity().getLayoutInflater().inflate(R.layout.inflatable_layout,rootLinearLayout,true);
    TextView t = (TextView) v.findViewById(R.id.text1);
    t.setText("Foo");
    View v2 = getActivity().getLayoutInflater().inflate(R.layout.inflatable_layout,rootLinearLayout,true);
    TextView t2 = (TextView) v2.findViewById(R.id.text1);
    t2.setText("Bar");

通过这样做,我最终得到了两个膨胀的视图。但是,第一个视图的 TextView 包含“Bar”,而第二个未更改。

有没有办法能够保持对我单独膨胀的视图的引用?

【问题讨论】:

    标签: android android-layout layout-inflater android-inflate


    【解决方案1】:

    要解决您的问题,只需更改:

    View v = inflater.inflate(R.layout.inflatable_layout,rootLinearLayout,true);
    

    到

    View v = inflater.inflate(R.layout.inflatable_layout,rootLinearLayout,false);
    rootLinearLayout.addView(v1);
    

    请注意,您现在必须手动将视图添加到布局中。

    (对 v2 执行相同操作)

    这样您应该会收到两个不同的参考。

    【讨论】:

      【解决方案2】:

      请试试这个:

      View v = getActivity().getLayoutInflater().inflate(R.layout.inflatable_layout,null); // Note the null replacing the "ViewGroup"
      TextView t = (TextView) v.findViewById(R.id.text1);
      t.setText("Foo");
      View v2 =    getActivity().getLayoutInflater().inflate(R.layout.inflatable_layout,null); // Note the null replacing the "ViewGroup"
      TextView t2 = (TextView) v2.findViewById(R.id.text1);
      t2.setText("Bar");
      
      // Manually append each layout to your linear layout.
      

      我认为这应该可行,因为没有定义根

      【讨论】:

      • 这应该会崩溃,因为你说你想将视图添加为null 的子视图。
      • 不,我认为您必须明确传递false,并传入实际所需的父级。我个人从不使用true 作为最后一个参数,我忘记了它是如何工作的。引用the docs, this version of inflate():“返回膨胀层次结构的根视图。如果提供了根并且attachToRoot 为真,则这是根;否则它是膨胀XML 文件的根。”
      • 我只是尝试将 null 作为父级传递,然后使用 AddView(v) 添加视图,得到了所需的行为,但也得到了“避免将 null 作为视图根传递”警告。传递父级(在本例中为 rootLinearLayout)并将最后一个参数设置为 false,然后通过 AddView(v) 手动添加视图也会产生所需的行为,并且不会出现警告。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-01-08
      • 1970-01-01
      相关资源
      最近更新 更多