Saturday, September 8, 2018

How to place elements side by side each other, programmatically?

Leave a Comment

I have a spinner, checkbox, and eddittext. Currently they are all one under each other but I want to make it so they are side by side each other

For example:

the spinner on the left, the edittext on the right of the spinner and then the checkbox on the right of the edittext.

Is this possible to do this programatically because these elements are created programatically.

xml layout

<?xml version="1.0" encoding="utf-8"?> <android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"     xmlns:app="http://schemas.android.com/apk/res-auto"     xmlns:tools="http://schemas.android.com/tools"     android:layout_width="match_parent"     android:layout_height="match_parent"     android:background="@color/colorBackground"     android:minHeight="170dp"     tools:context=".create"     tools:layout_editor_absoluteY="81dp"     >       <ScrollView xmlns:android="http://schemas.android.com/apk/res/android"         android:id="@+id/scrollView2"         android:layout_width="match_parent"         android:layout_height="438dp"         android:fillViewport="true"         app:layout_constraintEnd_toEndOf="parent"         app:layout_constraintHorizontal_bias="1.0"         app:layout_constraintStart_toStartOf="parent"         tools:layout_editor_absoluteY="0dp">           <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"             xmlns:app="http://schemas.android.com/apk/res-auto"             xmlns:tools="http://schemas.android.com/tools"             android:id="@+id/my_linearLayout"             android:layout_width="match_parent"             android:layout_height="match_parent"             android:orientation="vertical" >               <LinearLayout                 android:layout_width="match_parent"                 android:layout_height="wrap_content"                 android:orientation="vertical"                 android:id="@+id/verticalLayout"                 android:layout_below="@id/view2">              </LinearLayout>           </LinearLayout>           </ScrollView>      <android.support.design.widget.FloatingActionButton         android:id="@+id/fab"         android:layout_width="60dp"         android:layout_height="70dp"         android:layout_gravity="bottom|end"         android:layout_marginBottom="16dp"         android:layout_marginEnd="16dp"         android:layout_marginLeft="8dp"         android:layout_marginRight="16dp"         android:layout_marginStart="8dp"         android:src="@android:drawable/ic_input_add"         app:backgroundTint="@color/colorCreate"         app:elevation="6dp"         app:layout_constraintBottom_toBottomOf="parent"         app:layout_constraintEnd_toEndOf="parent"         app:layout_constraintHorizontal_bias="1.0"         app:layout_constraintStart_toStartOf="parent"         app:pressedTranslationZ="12dp"         android:tint="@color/colorBackground"/>       <View         android:id="@+id/subheading"         android:layout_width="match_parent"         android:layout_height="83dp"         android:layout_marginBottom="8dp"         android:layout_marginEnd="1dp"         android:layout_marginLeft="1dp"         android:layout_marginRight="1dp"         android:layout_marginStart="1dp"         android:layout_marginTop="2dp"         android:background="@color/colorBackground"         app:layout_constraintBottom_toBottomOf="parent"         app:layout_constraintEnd_toEndOf="parent"         app:layout_constraintHorizontal_bias="0.0"         app:layout_constraintStart_toStartOf="parent"         app:layout_constraintTop_toTopOf="parent"         app:layout_constraintVertical_bias="0.0"         />      <View         android:id="@+id/view"         android:layout_width="320dp"         android:layout_height="1dp"         android:layout_marginEnd="8dp"         android:layout_marginLeft="8dp"         android:layout_marginRight="8dp"         android:layout_marginStart="8dp"         android:layout_marginTop="76dp"         android:background="@color/colorText"         app:layout_constraintEnd_toEndOf="parent"         app:layout_constraintStart_toStartOf="parent"         app:layout_constraintTop_toTopOf="parent" />      <View         android:id="@+id/view2"         android:layout_width="320dp"         android:layout_height="1dp"         android:layout_marginEnd="8dp"         android:layout_marginLeft="8dp"         android:layout_marginRight="8dp"         android:layout_marginStart="8dp"         android:layout_marginTop="28dp"         android:background="@color/colorText"         app:layout_constraintEnd_toEndOf="parent"         app:layout_constraintStart_toStartOf="parent"         app:layout_constraintTop_toTopOf="parent" />      <TextView         android:id="@+id/textView"         android:layout_width="wrap_content"         android:layout_height="wrap_content"         android:layout_marginEnd="8dp"         android:layout_marginLeft="8dp"         android:layout_marginRight="8dp"         android:layout_marginStart="8dp"          android:layout_marginTop="12dp"         android:fontFamily="@font/droid_sans"         android:text="@string/done_label"         android:textColor="@color/colorText"         android:textSize="20sp"         app:layout_constraintEnd_toEndOf="parent"         app:layout_constraintStart_toEndOf="@+id/textView4"         app:layout_constraintTop_toBottomOf="@+id/view2" />      <TextView         android:id="@+id/textView4"         android:layout_width="wrap_content"         android:layout_height="wrap_content"         android:layout_marginBottom="8dp"         android:layout_marginEnd="128dp"         android:layout_marginRight="128dp"         android:layout_marginTop="8dp"         android:fontFamily="@font/droid_sans"         android:text="@string/aisle_label"         android:textColor="@color/colorText"         android:textSize="20sp"         app:layout_constraintBottom_toTopOf="@+id/view"         app:layout_constraintEnd_toEndOf="parent"         app:layout_constraintTop_toBottomOf="@+id/view2"         app:layout_constraintVertical_bias="1.0" />      <TextView         android:id="@+id/textView3"         android:layout_width="wrap_content"         android:layout_height="wrap_content"         android:layout_marginBottom="5dp"         android:layout_marginEnd="32dp"         android:layout_marginRight="32dp"         android:layout_marginTop="5dp"         android:fontFamily="@font/droid_sans"         android:text="@string/qty_label"         android:textColor="@color/colorText"         android:textSize="20sp"         app:layout_constraintBottom_toTopOf="@+id/view"         app:layout_constraintEnd_toStartOf="@+id/textView4"         app:layout_constraintTop_toBottomOf="@+id/view2"         app:layout_constraintVertical_bias="0.7" />      <TextView         android:id="@+id/textView2"         android:layout_width="wrap_content"         android:layout_height="wrap_content"         android:layout_marginBottom="8dp"         android:layout_marginEnd="8dp"         android:layout_marginLeft="8dp"         android:layout_marginRight="8dp"         android:layout_marginStart="8dp"         android:layout_marginTop="8dp"         android:fontFamily="@font/droid_sans"         android:text="@string/item_label"         android:textColor="@color/colorText"         android:textSize="20sp"         app:layout_constraintBottom_toTopOf="@+id/view"         app:layout_constraintEnd_toStartOf="@+id/textView3"         app:layout_constraintStart_toStartOf="parent"         app:layout_constraintTop_toBottomOf="@+id/view2"         app:layout_constraintVertical_bias="1.0" />   </android.support.constraint.ConstraintLayout> 

java code

public class create extends AppCompatActivity {       private LinearLayout mLinearLayout;     private ArrayList<SearchableSpinner> mSpinners;     private List<AppCompatButton> mButtons = new ArrayList<>();     private List<CheckBox> mCheckboxes = new ArrayList<>();     private List<TextView> mTextviews = new ArrayList<>();     private List<EditText> mEdittexts = new ArrayList<>();     private List<View> mViews = new ArrayList<>();     private Map<String, String> numberItemValues = new HashMap<>();     private Spinner spinner;     private TextView textview;     private CheckBox checkbox;     List<String> itemList = new ArrayList<>();     LinearLayout verticallayout,horizontalLayout;           @Override     protected void onCreate(Bundle savedInstanceState) {         super.onCreate(savedInstanceState);         setContentView(R.layout.activity_create);         getSupportActionBar().setDisplayHomeAsUpEnabled(true);           //Arrays         ArrayList<String> items = new ArrayList<>();         items.add(String.valueOf(mSpinners)); // add you selected item         mSpinners = new ArrayList<>();             //Initializing Variables Here         mLinearLayout = findViewById(R.id.my_linearLayout);         verticallayout = findViewById(R.id.verticalLayout);         textview = findViewById(R.id.textview);         checkbox = findViewById(R.id.checkbox);              //code for the add button to add more items         FloatingActionButton floatingActionButton =                 (FloatingActionButton) findViewById(R.id.fab);           floatingActionButton.setOnClickListener(new View.OnClickListener() {             @Override             public void onClick(View view) {                 Toast.makeText(getBaseContext(), "Item added!", Toast.LENGTH_SHORT).show();                 spinner = findViewById(R.id.spinner);                   createRow();                    // Handle ze click.              /*   final Spinner spinner = makeSpinner();                 mLinearLayout.addView(spinner);                   LinearLayout.LayoutParams layoutParams = (LinearLayout.LayoutParams) spinner.getLayoutParams();                 layoutParams.setMargins(5, 100, 10, 0); //top 70                  Resources resources = getResources();                 DisplayMetrics metrics = resources.getDisplayMetrics();                  layoutParams.height = (int) (70 * ((float) metrics.densityDpi / DisplayMetrics.DENSITY_DEFAULT)); //80                 layoutParams.width = (int) (240 * ((float) metrics.densityDpi / DisplayMetrics.DENSITY_DEFAULT)); //240                 spinner.setLayoutParams(layoutParams);*/                  final View newView = makeView();                 //Add a new view                 mLinearLayout.addView(newView);                 mViews.add(newView);  /*                  final EditText newEdittext = makeEdittext();                 mLinearLayout.addView(newEdittext);                 mEdittexts.add(newEdittext);   */                   final int listSize = mViews.size();                   //code for deleting the said item.                 newView.setOnClickListener(new View.OnClickListener() {                     //start                     @Override                     public void onClick(View view) {                          //when the 'new button' is pressed, alert shows if you are sure you want to delete the item or not.                          final View.OnClickListener context = this;                           AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(create.this);                           // set title                         alertDialogBuilder.setTitle("Delete Item");                          // set dialog message                         alertDialogBuilder                                 .setMessage("Are you sure you want to delete this item?")                                 .setCancelable(false)                                 .setPositiveButton("Yes", new DialogInterface.OnClickListener() {                                     public void onClick(DialogInterface dialog, int id) {                                         // if this button is clicked, close                                         // current activity                                           if (listSize > 0) {                                              mCheckboxes.get(listSize - 1).setVisibility(View.GONE);                                             mSpinners.get(listSize - 1).setVisibility(View.GONE);                                             mViews.get(listSize - 1).setVisibility(View.GONE);                                             mTextviews.get(listSize - 1).setVisibility(View.GONE);                                             mEdittexts.get(listSize - 1).setVisibility(View.GONE);                                             Toast.makeText(getBaseContext(), "Item removed.", Toast.LENGTH_SHORT).show();                                          }                                       }                                 })                                 .setNegativeButton("No", new DialogInterface.OnClickListener() {                                     public void onClick(DialogInterface dialog, int id) {                                         // if this button is clicked, just close                                         // the dialog box and do nothing                                         dialog.cancel();                                     }                                 });                          // create alert dialog                         AlertDialog alertDialog = alertDialogBuilder.create();                          // show it                         alertDialog.show();                       }                 });               /*    //Add a new checkbox                 final CheckBox newCheckbox = makeCheckbox();                 mLinearLayout.addView(newCheckbox);                  //TODO add checkbox to your list                 mCheckboxes.add(newCheckbox);*/                   final TextView newTextview = makeTextview();                 mLinearLayout.addView(newTextview);                 mTextviews.add(newTextview);                  //TODO Add the spinner on item selected listener to get selected items                 spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {                     @Override                     public void onItemSelected(AdapterView<?> parentView, View selectedItemView, int position, long id) {                         String currentItem = itemList.get(position);                         String aisleNumber = numberItemValues.get(currentItem);                         //TODO you can use the above aisle number to add to your text view                         //mTextviews.get(mTextviews.size() -1).setText(aisleNumber);                         newTextview.setText(aisleNumber);                     }                      @Override                     public void onNothingSelected(AdapterView<?> parentView) {                         //  code here                     }                  });               }         });       }       public void createRow(View view){          createRow(); //got      }       private void createRow() { //got          horizontalLayout = new LinearLayout(this);          LinearLayout.LayoutParams horizontalParams = new LinearLayout.LayoutParams(                 LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT);         horizontalLayout.setOrientation(LinearLayout.HORIZONTAL);         horizontalLayout.setLayoutParams(horizontalParams);          makeEdittext();         makeCheckbox();         makeSpinner();          verticallayout.addView(horizontalLayout);     }               //TODO OVERFLOW MENU     @Override     public boolean onCreateOptionsMenu(Menu menu) {         // Inflate the menu; this adds items to the action bar if it is present.         getMenuInflater().inflate(R.menu.create_menu, menu);         return true;     }      @Override     public boolean onOptionsItemSelected(MenuItem item) {          int id = item.getItemId();          if (id == R.id.action_settings) {             Intent startSettingsActivity = new Intent(this, AppCompatPreferenceActivity.class);             startActivity(startSettingsActivity);             //start the settings activity here.             return true;         }           else if (id == R.id.action_delete) {             //code to delete list here.             return true;          }          else if (id == R.id.action_gotoview) {               //takes the size of the list of spinners, for reference             ArrayList<Integer> spinnerList = new ArrayList<>();             for(int i = 0; i < mSpinners.size(); i++) {                 spinnerList.add(mSpinners.get(i).getSelectedItemPosition());               }             Bundle newBundle = new Bundle();             newBundle.putIntegerArrayList("arraylist", spinnerList);             Intent newIntent = new Intent(create.this, view.class);             newIntent.putExtra("extraBundle", newBundle);              startActivity(newIntent);                //code to go to view screen, aka intent             return true;         }            return super.onOptionsItemSelected(item);     }          //use a relative layout and specify which ones are to layout_toRightOf and layout_below      //DUPLICATING ITEMS WHEN FAB IS PRESSED//     private CheckBox makeCheckbox() {         //Create new Checkbox         CheckBox checkbox = new CheckBox(this);          // Setup layout           LinearLayout.LayoutParams checkParams = new LinearLayout.LayoutParams(                 LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT);         checkParams.setMargins(10, 10, 10, 10);         checkParams.gravity = Gravity.LEFT;          checkbox.setLayoutParams(checkParams);         horizontalLayout.addView(checkbox);           return checkbox;     }        private TextView makeTextview() {         //create new textview         TextView textview = new TextView(this);          //setup layout          LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(                 LinearLayout.LayoutParams.MATCH_PARENT,                 LinearLayout.LayoutParams.WRAP_CONTENT);         textview.setLayoutParams(layoutParams);         textview.setTextSize(30);          return textview;     }       private EditText makeEdittext() {         //create new edittext         EditText edittext = new EditText(this);         /* //setup layout         final LinearLayout.LayoutParams lparams = new LinearLayout.LayoutParams(70, 50); // Width , height         edittext.setLayoutParams(lparams);*/           LinearLayout.LayoutParams editParams = new LinearLayout.LayoutParams(                 LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT);         editParams.setMargins(10, 10, 10, 10);         editParams.width = 70;         editParams.height = 50;           edittext.setLayoutParams(editParams);         horizontalLayout.addView(edittext);            edittext.setInputType(InputType.TYPE_CLASS_NUMBER | InputType.TYPE_NUMBER_FLAG_DECIMAL | InputType.TYPE_NUMBER_FLAG_SIGNED);         edittext.setHint("qty");          return edittext;      }         private View makeView() {         //create new View          View view = new View(this);         view.setBackgroundColor(Color.parseColor("#ffffff"));         LinearLayout.LayoutParams layoutParams =  new LinearLayout.LayoutParams( LinearLayout.LayoutParams.MATCH_PARENT, 100);         new LinearLayout.LayoutParams( LinearLayout.LayoutParams.WRAP_CONTENT, 50);         //LinearLayout.LayoutParams.MATCH_PARENT,         // LinearLayout.LayoutParams.WRAP_CONTENT);         view.setClickable(true);           view.setLayoutParams(layoutParams);           //setup layout          return view;       }           private Spinner makeSpinner() {         //opens csv         InputStream inputStream = getResources().openRawResource(R.raw.shopitems);         CSVFile csvFile = new CSVFile(inputStream);         //TODO I made this variable global, declared it at the very top of this file         itemList = csvFile.read();          //Create new spinner         // SearchableSpinner spinner = (SearchableSpinner) new Spinner(this, Spinner.MODE_DROPDOWN);         SearchableSpinner spinner = new SearchableSpinner(this);           // Setup layout          LinearLayout.LayoutParams spinnerParams = new LinearLayout.LayoutParams(                 LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT);         spinnerParams.setMargins(10, 10, 10, 10);         spinnerParams.gravity = Gravity.LEFT;          Resources resources = getResources();         DisplayMetrics metrics = resources.getDisplayMetrics();          spinnerParams.height = (int) (70 * ((float) metrics.densityDpi / DisplayMetrics.DENSITY_DEFAULT)); //80         spinnerParams.width = (int) (240 * ((float) metrics.densityDpi / DisplayMetrics.DENSITY_DEFAULT)); //240            spinner.setLayoutParams(spinnerParams);         horizontalLayout.addView(spinner);          MyListAdapter adapter = new MyListAdapter(this, R.layout.listrow, R.id.txtid, itemList);           spinner.setAdapter(adapter);          //Add it to your list of spinners so you can retrieve their data when you click the getSpinner button         mSpinners.add(spinner);         return spinner;     }        private class CSVFile {         InputStream inputStream;          public CSVFile(InputStream inputStream) {             this.inputStream = inputStream;         }          public List<String> read() {              List<String> resultList = new ArrayList<String>();             BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));             try {                 String line;                 while ((line = reader.readLine()) != null) {                     String[] row = line.split(",");                     //TODO I edited this part so that you'd add the values in our new hash map variable                     numberItemValues.put(row[1], row[0]);                     resultList.add(row[1]);                 }             } catch (IOException e) {                 Log.e("Main", e.getMessage());             } finally {                 try {                     inputStream.close();                 } catch (IOException e) {                     Log.e("Main", e.getMessage());                 }             }             return resultList;         }     }} 

I get an error on this line:

spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {

error:

E/AndroidRuntime: FATAL EXCEPTION: main java.lang.NullPointerException

4 Answers

Answers 1

Set your linear layout orientation to horizontal

<LinearLayout         xmlns:android="http://schemas.android.com/apk/res/android"         xmlns:app="http://schemas.android.com/apk/res-auto"         xmlns:tools="http://schemas.android.com/tools"         android:id="@+id/my_linearLayout"         android:layout_width="match_parent"         android:layout_height="match_parent"         android:orientation="horizontal"> 

Answers 2

Try this way

home_activity.xml

<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"     android:layout_width="match_parent"     android:layout_height="match_parent"     android:orientation="vertical">      <Button         android:id="@+id/button"         android:layout_width="wrap_content"         android:layout_height="wrap_content"         android:layout_gravity="center_horizontal"         android:onClick="createRow"         android:text="Create Row" />      <LinearLayout         android:id="@+id/verticalLayout"         android:layout_width="match_parent"         android:layout_height="match_parent"         android:orientation="vertical">      </LinearLayout> </LinearLayout> 

HomeActivity.java

public class HomeActivity extends AppCompatActivity {     LinearLayout verticallayout, horizontalLayout;     int width;       @Override     protected void onCreate(Bundle savedInstanceState) {         super.onCreate(savedInstanceState);         setContentView(R.layout.home_activity);         verticallayout = findViewById(R.id.verticalLayout);         DisplayMetrics displayMetrics = new DisplayMetrics();         getWindowManager().getDefaultDisplay().getMetrics(displayMetrics);         width = displayMetrics.widthPixels;      }      public void createRow(View view) {         createRow();     }      private void createRow() {         horizontalLayout = new LinearLayout(this);         LinearLayout.LayoutParams horizontalParams = new LinearLayout.LayoutParams(                 LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT);         horizontalLayout.setOrientation(LinearLayout.HORIZONTAL);         horizontalLayout.setLayoutParams(horizontalParams);          createSpinner();         createCheckbox();         createEditText();          verticallayout.addView(horizontalLayout);     }      private void createEditText() {         EditText editText = new EditText(this);          LinearLayout.LayoutParams editParams = new LinearLayout.LayoutParams((width/3), convertDpToPixel(40));         editParams.setMargins(10, 10, 10, 10);          editText.setLayoutParams(editParams);         editText.setHint("Enter something");         editText.setTextSize(14f);         horizontalLayout.addView(editText);     }       private void createCheckbox() {         CheckBox checkBox = new CheckBox(this);          LinearLayout.LayoutParams checkParams = new LinearLayout.LayoutParams((width/3), convertDpToPixel(40));         checkParams.setMargins(10, 10, 10, 10); //        checkParams.gravity = Gravity.LEFT;          checkBox.setLayoutParams(checkParams);         checkBox.setText("Is Applicable");         horizontalLayout.addView(checkBox);      }      private void createSpinner() {         Spinner spinner = new Spinner(this);         LinearLayout.LayoutParams spinnerParams = new LinearLayout.LayoutParams((width/3), convertDpToPixel(40));;         spinnerParams.setMargins(10, 10, 10, 10); //        spinnerParams.gravity = Gravity.LEFT;          spinner.setLayoutParams(spinnerParams);         String[] item = new String[]{"item1","item2","item3","item4","item5","item6","item7"};         ArrayAdapter<String> spinnerArrayAdapter = new ArrayAdapter<String>(this,android.R.layout.simple_spinner_dropdown_item, item);         spinner.setAdapter(spinnerArrayAdapter);         spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {             @Override             public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {                 System.out.println(parent.getSelectedItem().toString());             }              @Override             public void onNothingSelected(AdapterView<?> parent) {              }         });          horizontalLayout.addView(spinner);     }       public int convertDpToPixel(int dp) {         DisplayMetrics metrics = getResources().getDisplayMetrics();         return dp * ((int) metrics.densityDpi / DisplayMetrics.DENSITY_DEFAULT);     }  } 

may be this code generate some margin problem, but u can solve it by managing the value of Params.setMargins(10, 10, 10, 10)

let me know if any concern.

Answers 3

I was able to achieve this by using a static Linear Layout in XML ( Vertical orientation ) and added horizontal rows of the elements dynamically.

layout.xml

<?xml version="1.0" encoding="utf-8"?> <RelativeLayout     xmlns:android="http://schemas.android.com/apk/res/android"     android:layout_width="match_parent"     android:layout_height="match_parent">     <Button         android:id="@+id/button"         android:layout_width="wrap_content"         android:layout_height="wrap_content"         android:layout_alignParentTop="true"         android:layout_centerHorizontal="true"         android:gravity="right"         android:onClick="createRow"         android:text="Create Row" />      <LinearLayout         android:layout_width="match_parent"         android:layout_height="wrap_content"         android:orientation="vertical"         android:id="@+id/verticalLayout"         android:layout_below="@id/button">      </LinearLayout> </RelativeLayout> 

Activity to add Layout Dynamically

public class MyLayoutActivity extends AppCompatActivity {      LinearLayout verticallayout,horizontalLayout;      @Override     protected void onCreate(@Nullable Bundle savedInstanceState) {         super.onCreate(savedInstanceState);         setContentView(R.layout.layout_poc);          verticallayout = findViewById(R.id.verticalLayout);      }      public void createRow(View view){          createRow();      }      private void createRow() {          horizontalLayout = new LinearLayout(this);          LinearLayout.LayoutParams horizontalParams = new LinearLayout.LayoutParams(                 LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT);         horizontalLayout.setOrientation(LinearLayout.HORIZONTAL);         horizontalLayout.setLayoutParams(horizontalParams);          createSpinner();         createCheckbox();         createEditText();          verticallayout.addView(horizontalLayout);     }      private void createEditText() {         EditText editText = new EditText(this);          LinearLayout.LayoutParams editParams = new LinearLayout.LayoutParams(                 LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT);         editParams.setMargins(10, 10, 10, 10);          editText.setLayoutParams(editParams);         horizontalLayout.addView(editText);     }       private void createCheckbox() {         CheckBox checkBox = new CheckBox(this);          LinearLayout.LayoutParams checkParams = new LinearLayout.LayoutParams(                 LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT);         checkParams.setMargins(10, 10, 10, 10);         checkParams.gravity = Gravity.LEFT;          checkBox.setLayoutParams(checkParams);         horizontalLayout.addView(checkBox);      }      private void createSpinner() {          Spinner spinner = new Spinner(this);         //ArrayAdapter<String> spinnerArrayAdapter = new ArrayAdapter<String>(this,android.R.layout.simple_spinner_dropdown_item, spinnerArray);         //spinner.setAdapter(spinnerArrayAdapter);         LinearLayout.LayoutParams spinnerParams = new LinearLayout.LayoutParams(                 LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT);         spinnerParams.setMargins(10, 10, 10, 10);         spinnerParams.gravity = Gravity.LEFT;          spinner.setLayoutParams(spinnerParams);         horizontalLayout.addView(spinner);     } } 

Add the data to your spinner in array adapter according to your logic. you can change Layout params as per your design. My code gives output like below image:

Output

Answers 4

as other answers are suggesting you can always create views dynamically. but what I think you should do since you haven't accept any of these answers is to create your desired XML row and then you can add that view to your layout

LayoutInflater inflater = LayoutInflater.from(context); View v = inflater.inflate(R.layout.yourxmlrow, null, false); linearLayout.addView(v); 
If You Enjoyed This, Take 5 Seconds To Share It

0 comments:

Post a Comment