javaandroidsetcontentview

Android setContentview(scroll) hides the ConstraintLayout objects at the back


I am new to android and I created a ScrollView and inside it, added a vertical linear layout which contains TextViews and pickers. All of these were created programmatically. My problem is on setContentView(scroll) line. It seems to cover all the objects I created (not programmatically) on the ConstraintLayout at the back. But I already set the height of my dynamic ScrollView to 800. How can I display the 4 buttons at the back of the ScrollView?

See screenshots:

non dynamic objects in constraintlayout

programmatically created objects in linearlayout inside scrollview

Here is the code.

        ScrollView scroll = new ScrollView(this);
        
        scroll.setLayoutParams(new LayoutParams(LayoutParams.MATCH_PARENT,
                800));
        scroll.setFillViewport(true);
      
        setContentView(scroll); //here is the line with issue

        LinearLayout linearLayout = new LinearLayout(this);
        linearLayout.setOrientation(LinearLayout.VERTICAL);
        LayoutParams lp1 = new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
        linearLayout.setLayoutParams(lp1);

        scroll.addView(linearLayout);
        
        for( int i = 0; i < res2.getCount(); i++ )
        {
            NumberPicker numberPicker = new NumberPicker(this);
            numberPicker.setMinValue(0);
            numberPicker.setMaxValue(100);
            TextView textView = new TextView(this);
            textView.setText(/*textArray[i] + " " +*/ res2.getString(1));
            linearLayout.addView(textView);
            linearLayout.addView(numberPicker);

            res2.moveToNext();
        }

Thank you in advance for your help.


Solution

  • Declare your LinearLayout on your xml instead of add it programmatically. You will always have the linear and the scrollview. Then fill the Linear with the desired view as you do inside for loop. That way you will ensure that your views are in the right position with the right size.