在膨胀多个实例时,无法获得对视图的单独引用

时间:2015-01-14 20:33:19

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

我的目的是在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",第二个视图不包含。

有没有办法能够维持对我单独膨胀的观点的引用?

2 个答案:

答案 0 :(得分: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做同样的事)

这样你就会收到两个不同的引用。

答案 1 :(得分:0)

请试试这个:

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.

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