add Layout programmatically inside another one

前端 未结 1 696
孤城傲影
孤城傲影 2021-02-13 11:13

I have an xml file (option_element.xml) that contains a ImageView and a TextView

 


        
1条回答
  •  爱一瞬间的悲伤
    2021-02-13 11:53

    The inflate(int resource, ViewGroup root) method return root if root is not null, thus to_add.findViewById() equals options_layout.findViewById() and it always return the Views in the first position. Change as following should help:

    LinearLayout options_layout = (LinearLayout) findViewById(R.id.options_list);
    String[] options = getActivity().getResources().getStringArray(R.array.options);
    for (int i = 0; i < options.length; i++) {
        View to_add = inflater.inflate(R.layout.options_element,
                    options_layout);
    
        TextView text = (TextView) to_add.findViewById(R.id.text);
        text.setText(options[i]);
        text.setTypeface(FontSelector.getBold(getActivity()));
    
    }
    

    to:

    LinearLayout options_layout = (LinearLayout) findViewById(R.id.options_list);
    String[] options = getActivity().getResources().getStringArray(R.array.options);
    for (int i = 0; i < options.length; i++) {
        View to_add = inflater.inflate(R.layout.options_element,
                    options_layout,false);
    
        TextView text = (TextView) to_add.findViewById(R.id.text);
        text.setText(options[i]);
        text.setTypeface(FontSelector.getBold(getActivity()));
        options_layout.addView(to_add);
    }
    

    0 讨论(0)
提交回复
热议问题