Add multiple custom views to layout programmatically

后端 未结 3 1970
無奈伤痛
無奈伤痛 2020-12-24 06:30

If I for example have empty layout like this:

layout1.xml



        
3条回答
  •  醉梦人生
    2020-12-24 06:47

    layout1.xml contains ScrollView as parent layout and main LinearLayout as child if no row item more screen size ScrollView handle overflow item with scroll:

    layout1.xml

    
    
        
    
        
    
    

    Use LayoutInflater to add row item to parent LinearLayout:

    private LinearLayout my_linear_layout;
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.layout1);
        my_linear_layout = (LinearLayout) findViewById(R.id.my_linear_layout);
    
        for (int i = 1; i <= 5; i++) {
            View view = LayoutInflater.from(this).inflate(R.layout.layout2, null);
            TextView button1 = (TextView) view.findViewById(R.id.button1);
            Button button2 = (Button) view.findViewById(R.id.button2);
            TextView button3 = (TextView) view.findViewById(R.id.button3);
    
            button1.setText("HELLO " + i);
            button2.setText("HELLO " + i);
            button3.setText("HELLO " + i);
            my_linear_layout.addView(view);
        }
    }
    

提交回复
热议问题