Search code examples
javaandroidlayoutandroid-alertdialogprogrammatically-created

Android scrollable AlertDialog programmatically


How can i programmatically make my AlertDialog Scrollable ?

My AlertDialog is defined like this :

private void DisplayAlertChoice(String title, String msg, final int pos)
{       
    alert = new AlertDialog.Builder(this);
    alert.setTitle(title);
    final LinearLayout layout = new LinearLayout(this);
    layout.setOrientation(LinearLayout.VERTICAL);
     CheckBox[] t=new CheckBox[15];
     for (i=0;i<currentBattery.temperatureNumber;i++)
     {               
         t[i]=new CheckBox(this);
         t[i].setText("title");
         t[i].setChecked(false);
         t[i].setOnCheckedChangeListener(this);

         layout.addView(t[i]);      
     }
    alert.setView(layout);      
    alert.show();   

}

I tried a few solutions found in the net but didn't work for me.

Can someone give me a pertinent solution to make it scrollable programmatically ?


Solution

  • i tried it, but it forces my app to stop.

    ScrollView can have just a child. It is an Android constraint. So, doing

        final LinearLayout layout = new LinearLayout(this);
        ScrollView scrollView = new ScrollView(this);
        layout.setOrientation(LinearLayout.VERTICAL);
         CheckBox[] t=new CheckBox[15];
         for (i=0;i<currentBattery.temperatureNumber;i++)
         {               
             t[i]=new CheckBox(this);
             t[i].setText("title");
             t[i].setChecked(false);
             t[i].setOnCheckedChangeListener(this);
    
             scrollView.addView(t[i]);      
         }
    

    will make your app crash, because you are adding more than one child to the ScrollView. But if you do

    final LinearLayout layout = new LinearLayout(this);
    layout.setOrientation(LinearLayout.VERTICAL);
     CheckBox[] t=new CheckBox[15];
     for (i=0;i<currentBattery.temperatureNumber;i++)
     {               
         t[i]=new CheckBox(this);
         t[i].setText("title");
         t[i].setChecked(false);
         t[i].setOnCheckedChangeListener(this);
    
         layout.addView(t[i]);      
     }
     final ScrollView scrollView = new ScrollView(this); 
     scrollView.addView(layout);
    

    it should work smoothly.