ravelinx ravelinx - 5 months ago 14
Java Question

Dynamic resizing linear layout depending on location in android studio

Im using android studio to develop an app, I want to have a table with a list of options that changes depending on location, for example if I am in NYC I want to display 3 options but if I'm in San Diego I want 5. My idea was to have a Linear Layout that has wrap_content as height with other linear layouts inside of it for each option. The problem is that I don't know how to modify(add/remove) the inside layouts to it or if there is a better way to implement this idea. Also the user is capable of selecting one of the options, they are clickable.

Here are some examples

enter image description here
enter image description here

Answer

Here is the code what I have tried for adding a linear layout dynamically, it worked :). First load the parent layout in which you want to dynamically create the linear layouts. Then you have to decide the number of layouts to be displayed and pass it to the 'NumberOfLayouts' variable in the code it will dynamically create the linear layouts.

 /*Loading the Parent Layout*/
 LinearLayout ParentLayout = (LinearLayout)findViewById(R.id.ParentLayout);

    /*Dynamically creating your linear layouts*/
    for(int i=0; i<NumberOfLayouts; i++){
      LinearLayout linearLayout = new LinearLayout(getApplication());

        TextView textView = new TextView(this);
        textView.setText("Sample Text");

        linearLayout.addView(textView);

        ParentLayout.addView(linearLayout);

        /*Adding listener for the individual layouts*/
        linearLayout.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
              //Your code or method to be executed while clicking the dynamically created linear layout
            }
        });
    }
Comments