setText并没有为所有膨胀的TextView提供价值

时间:2016-02-28 08:46:40

标签: android

我有两种布局notification.xmlnotification_fragment.xml

notification_fragment.xml已经有了TextView。

notification_fragment.xml内有一个ID为linear的LinearLaout。

我试图在notification_fragment.xml内多次notification.xml充气,如以下代码所示

public View onCreateView(LayoutInflater inflater, ViewGroup container,
            Bundle savedInstanceState) {
        rootView = inflater.inflate(R.layout.notification, container,
                false);

        linear = (LinearLayout) rootView.findViewById(R.id.linear);
        childView = inflater.inflate(R.layout.notification_fragment, linear);
        for (int i = 0; i<= 10; i++){
            childView = inflater.inflate(R.layout.notification_fragment, linear);
            TextView txt = (TextView) childView.findViewById(R.id.textView1);
            txt.setText("welcome");
            txt.setTag(i);
        }
        return rootView;
    } 

我的代码存在的问题是,它txt.setText将TextView的值设置为welcome仅用于第一个被充气的视图,而其余9个视图具有我硬编码的默认值在我的xml中。

如何让所有文字视图显示文字welcome

2 个答案:

答案 0 :(得分:1)

最后我自己弄明白了。感谢所有尝试过的人。

@Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
            Bundle savedInstanceState) {
    rootView = inflater.inflate(R.layout.notification, container, false);

    linear = (LinearLayout) rootView.findViewById(R.id.linear);

    for (int i = 0; i <= 10; i++) {

        childView = inflater
                .inflate(R.layout.notification_fragment, linear);

        TextView txt = (TextView) childView.findViewById(R.id.textView1);
        txt.setText("welcome");
        txt.setId(i);
    }

    return rootView;
}

每次Im膨胀视图时,我都必须设置文本视图的id。

答案 1 :(得分:1)

1.您可以使用if条件。

if(i==0){
 txt.setText("welcome");
}
  1. 您可以使用do-while循环 3。

    childView = inflater.inflate(R.layout.notification_fragment, linear);
    for (int i = 0; i<= 10; i++){
       linear);
        TextView txt = (TextView) childView.findViewById(R.id.textView1);
        txt.setText("welcome");
        txt.setTag(i);
        //  add this view to its parent view. i.e. here 'childView' 
        childView.add(txt);
    }
    return rootView;