0

I am trying to make my layout so that I have these two elements: a checkbox and a dropdown, which are side by side, and it has a button like background.

Currently, I have my design so it's just the elements one under each other, like shown in the second image. I want it so it looks like:

What I want my layout to look like

what it currently looks like::

enter image description here

PLEASE NOTE: imagine the word 'flour' is the Spinner item (ignore the number 3)

Thanks!

Following is my create.java code:

public class create extends AppCompatActivity {


    private LinearLayout mLinearLayout;
    private ArrayList<SearchableSpinner> mSpinners;
    //TODO add the below list of buttons and checkboxes
    private List<AppCompatButton> mButtons = new ArrayList<>();
    private List<CheckBox> mCheckboxes = new ArrayList<>();
    //Button buttontest;





    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_create);
        getSupportActionBar().setDisplayHomeAsUpEnabled(true);


        mSpinners = new ArrayList<>();

        mLinearLayout = findViewById(R.id.my_linearLayout);

        //mLinearLayout.addView(makeSpinner());    // First spinner








        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();



                // Handle the click.
                Spinner spinner = makeSpinner();
                mLinearLayout.addView(spinner); //Add another 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);




                //Add a new button
                AppCompatButton newButton = makeButton();
                mLinearLayout.addView(newButton);      // Add another button
                //TODO add button to the list
                mButtons.add(newButton);
                final int listSize = mButtons.size();








                newButton.setOnClickListener(new View.OnClickListener() {
//start

                    @Override
                    public void onClick(View view) {



                        final View.OnClickListener context = this;







                        AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(create.this);


// set title
                        alertDialogBuilder.setTitle("Your Title");

// set dialog message
                        alertDialogBuilder
                                .setMessage("Click yes to exit!")
                                .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) {

                                            mButtons.get(listSize - 1).setVisibility(View.GONE);
                                            mCheckboxes.get(listSize - 1).setVisibility(View.GONE);
                                            mSpinners.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
                CheckBox newCheckbox = makeCheckbox();
                mLinearLayout.addView(newCheckbox);

                //TODO add checkbox to your list
                mCheckboxes.add(newCheckbox);




            }
        });



    }


//DUPLICATING ITEMS WHEN + IS PRESSED

    private CheckBox makeCheckbox() {
        //Create new Checkbox
        CheckBox checkbox = new CheckBox(this);

        // Setup layout
        LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(
                LinearLayout.LayoutParams.MATCH_PARENT,
                LinearLayout.LayoutParams.WRAP_CONTENT);
        checkbox.setLayoutParams(layoutParams);
        return checkbox;
    }


    private AppCompatButton makeButton() { //creates new buttons i need
        //Create new Button
        AppCompatButton button = new AppCompatButton(this);
        // code for deleting the buttons i need //
        //buttontest.setOnClickListener(new View.OnClickListener() {
         //   @Override
         //   public void onClick(View v) {







                //makeCheckbox().setVisibility(View.GONE);
                //buttontest.setVisibility(View.GONE);
                //TODO when you want to make one of them gone do the following
                //Last button disappears
            //    if(mButtons.size() > 0) {
            //        mButtons.get(mButtons.size()-1).setVisibility(View.GONE);
            //        mButtons.remove(mButtons.size()-1);
              //  }

                //Last checkbox disappears
                //if(mCheckboxes.size() > 0) {
                  //  mCheckboxes.get(mCheckboxes.size()-1).setVisibility(View.GONE);
                    //mCheckboxes.remove(mCheckboxes.size()-1);
               // }


                //Last checkbox disappears
              //  if(mSpinners.size() > 0) {
              //      mSpinners.get(mSpinners.size()-1).setVisibility(View.GONE);
              //      mSpinners.remove(mSpinners.size()-1);
              //  }

                //Please note that the number within get() is the index of the buttons or
                //checkboxes you added so there could
                //be any number of items depends on how many you added

          //  }
      //  });






        // Setup layout
        LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(
                LinearLayout.LayoutParams.MATCH_PARENT,
                LinearLayout.LayoutParams.WRAP_CONTENT);
        button.setBackgroundColor(Color.parseColor("#ffffff"));


        return button;
    }

    private Spinner makeSpinner() {
        //opens csv
        InputStream inputStream = getResources().openRawResource(R.raw.shopitems);
        CSVFile csvFile = new CSVFile(inputStream);
        List<String> itemList = csvFile.read();

        //Create new spinner
       // SearchableSpinner spinner = (SearchableSpinner) new Spinner(this, Spinner.MODE_DROPDOWN);
        SearchableSpinner spinner = new SearchableSpinner(this);




        // Setup layout
        LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(
                LinearLayout.LayoutParams.MATCH_PARENT,
                LinearLayout.LayoutParams.WRAP_CONTENT);
        spinner.setLayoutParams(layoutParams);
        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;
    }



    //csv file code
    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(",");
                    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;
        }
    }
}

xml code as follows:

<?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">





    <Button
        android:id="@+id/buttontest"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginBottom="8dp"
        android:layout_marginTop="8dp"
        android:text="Button"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="@+id/my_linearLayout" />


    <ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
        android:id="@+id/scrollView2"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:fillViewport="true">


        <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>


    </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" />


    <View
        android:id="@+id/subheading"
        android:layout_width="match_parent"
        android:layout_height="111dp"
        android:layout_marginBottom="384dp"
        android:background="@color/colorBackground"
        app:layout_constraintBottom_toBottomOf="@+id/scrollView2"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintHorizontal_bias="0.0"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

    <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>
  • 3
    can you add more clarity to your question using pictures? Like how it is, and how it should be? I can't seem to recreate your layout due to some missing resources. – Jacob Celestine Aug 12 '18 at 07:12
  • Hi, sorry. I have already got the image of what it should look like in mypost ^ (created using some designs) and I have just added the image of what it looks like now –  Aug 12 '18 at 07:29
  • can you add a basic blueprint of what you want?it will be extremely helpful for you and us.cos when pastuing your layout code some things are getting messed up... – Aishik kirtaniya Aug 12 '18 at 13:19
  • What do you mean by blueprint? All I can give you are the images I already had in my post, because I programmed my code to add dropdowns and checkboxes etc so they aren't manually on my design for me to show you a blueprint. To clarify the images, where it says flour, imagine that as the dropdown. and imagine the number beside it as the edittext –  Aug 12 '18 at 19:26
  • TBH, your question is not at all understandable to me. I'm sorry but otherwise I'd have helped you. – Jacob Celestine Aug 13 '18 at 04:42
  • Hi, sorry. I've tried to reword my question. if you still have any questions let me know –  Aug 13 '18 at 04:54
  • so basically, you want the pop up box to have a spinner, a checkbox and a button, side by side, right? And the reference _the white button is the white button_ refers to the circle at the end? Since your background is white, I can't see any other buttons. – Jacob Celestine Aug 13 '18 at 05:09
  • I'm just calling the pop up button the pop up box because it has a shadow and looks like it's popping up. So - the pop up button refers to the white long box that spans the width of the screen you see. The circle at the end refers to the checkbox (it should be square because it is square in android by default). The checkbox is *on top* of the 'pop up button' –  Aug 13 '18 at 05:14
  • 1
    so basically - I want to find a way to put elements such as a dropdown, and a checkbox **on top** of the button. - Just know that I am programming it so these items are duplicated so I can't do this in xml easily –  Aug 13 '18 at 05:19
  • the background is a grey-ish colour, the pop up button is the white. –  Aug 13 '18 at 05:28
  • can you provide a combined image, what is now and what you wanted. It confusing for me also. – Ranjan Aug 13 '18 at 07:27
  • I already put what It currently looks like and what I wante it to look like in my post. –  Aug 13 '18 at 07:30
  • Does that make sense –  Aug 13 '18 at 19:03

2 Answers2

0

Use this method ViewGroup#addView (View child, int index) so that you can specify the position to which the new child should be added.

Example:

mLinearLayout.addView(newButton, 0);
Bertram Gilfoyle
  • 8,353
  • 5
  • 36
  • 61
  • Tried adding that but my app crashed when I press the FAB (which is suppose to duplicate items) –  Aug 11 '18 at 22:34
  • @Magic_Whizz can you share the stacktrace of the crash – Bertram Gilfoyle Aug 13 '18 at 07:26
  • Added logcat into post –  Aug 13 '18 at 08:38
  • When using `LayoutInflater#inflate()` method, pass `attachToRoot` as false like `inflater.inflate(R.layout.my_layout, parent, false)`. Check [this](https://stackoverflow.com/questions/51729036/what-is-layoutinflater-and-how-do-i-use-it-properly/51729037#51729037) post for detailed explanation. – Bertram Gilfoyle Aug 13 '18 at 08:48
  • hmm but I haven't used that method? –  Aug 13 '18 at 08:49
  • Let's discuss in [chat](https://chat.stackoverflow.com/rooms/177857/room-for-anees-and-magic-whizz) – Bertram Gilfoyle Aug 13 '18 at 08:52
0

I want to find a way to put elements such as a dropdown, and a checkbox on top of the button

Based on my understanding of this, if you want a spinner and a checkbox side by side, programmatically, do this:

First change:

<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>

to:

<RelativeLayout
    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"/>

Now in you java code, for a spinner and checkbox to come side by side, here's the code:

floatingActionButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                RelativeLayout.LayoutParams params1 = new RelativeLayout.LayoutParams(WindowManager.LayoutParams.WRAP_CONTENT, WindowManager.LayoutParams.WRAP_CONTENT);
                RelativeLayout.LayoutParams params2 = new RelativeLayout.LayoutParams(WindowManager.LayoutParams.WRAP_CONTENT, WindowManager.LayoutParams.WRAP_CONTENT);
                // Handle the click.

                //Make a spinner
                Spinner spinner = makeSpinner();
                spinner.setId(1);
                mLinearLayout.addView(spinner,params1);

                //Add a new checkbox
                CheckBox newCheckbox = makeCheckbox();
                newCheckbox.setId(2);
                params2.addRule(RelativeLayout.RIGHT_OF, spinner.getId());
                mLinearLayout.addView(newCheckbox,params2);
            }
        });

I changed your layout a bit and tried this code on my phone, and here's the result I got:

Screenshot

Now again, this is from my understanding of your question. If this is what you were looking for, great! Otherwise, let's discuss more based on this answer.

Jacob Celestine
  • 1,519
  • 10
  • 21
  • generateViewId equires API level 17., but my current is 16. –  Aug 14 '18 at 20:51
  • Is there a way to make it so I can use it for levels below 17? because I kind of need it on 16 –  Aug 15 '18 at 03:27
  • I've changed the answer accordingly. You might have to reinstall the app while testing. – Jacob Celestine Aug 15 '18 at 05:37
  • for: spinner.setId(1); it says expected resource of type id –  Aug 15 '18 at 06:04
  • yeah but it would still work, try it out. If you must get rid of it, refer: [link1](https://stackoverflow.com/questions/6790623/programmatic-views-how-to-set-unique-ids) or [link2](https://stackoverflow.com/questions/24822953/how-to-assign-unique-ids-to-dynamically-created-views) or [link3](https://gist.github.com/omegasoft7/fdf7225a5b2955a1aba8) – Jacob Celestine Aug 15 '18 at 06:16
  • got this error: Caused by: java.lang.ClassCastException: android.widget.RelativeLayout cannot be cast to android.widget.LinearLayout –  Aug 15 '18 at 06:20
  • 1
    @Magic_Whizz That might be because in your java file you didn't change _LinearLayout my_linearLayout;_ to _Relativelayout my_linearLayout;_ – Jacob Celestine Aug 15 '18 at 06:21
  • Should I change all 'LinearLayout' I find in the 'find search' and change them to Relative Layout, because I havelinear layout params etc –  Aug 15 '18 at 06:23
  • Let us [continue this discussion in chat](https://chat.stackoverflow.com/rooms/178057/discussion-between-jacob-celestine-and-magic-whizz). – Jacob Celestine Aug 15 '18 at 06:28
  • Just quickly, would it be possible if I duplicated to elelemnts *inside* a linear layout, which is in the whole mLinearLayout: so like, each dropdown set will have it's own linear layout background colour? –  Aug 17 '18 at 02:55
  • I don't understand what you're asking, can you be more clear? – Jacob Celestine Aug 17 '18 at 05:51
  • So you know I'm adding my spinner and checkbox to the mLinearLayout, right? I was wondering if - I can add a separate linear layout to the duplication process, in which the spinner and checkbox can sit *on top* of that. Then that whole body is duplicated. Do you get what I mean? You told me it's not possible to put a spinner on top of a button, but is it possible to put a spinner on top of a linearlayout? –  Aug 17 '18 at 05:58
  • _is it possible to put a spinner on top of a linearlayout?_ yes, absolutely. – Jacob Celestine Aug 17 '18 at 06:31
  • so would that work in my situation if I just duplicated it etc . –  Aug 17 '18 at 06:43
  • 1
    okay so you mean like create a linearlayout with buttons and spinner, and then just keep duplicating that for as long as you need, right? You could do that. – Jacob Celestine Aug 17 '18 at 07:02
  • Hi, sorry. I managed to add a 'view' box to my duplication process. Now, how would I put the spinner and checkbox *on top* of the box? So that the coloured box is like the background of the spinner and checkbox, if you get what I mean (from previous convos) –  Aug 22 '18 at 07:54
  • programmatically? just add the spinner and checkbox to the 'view'. If you're using xml, just put your spinner and checkbox between `` – Jacob Celestine Aug 22 '18 at 08:09
  • how do I add it to the 'view' though? –  Aug 22 '18 at 09:33
  • 1
    Check [this](https://stackoverflow.com/questions/6216547/android-dynamically-add-views-into-view) – Jacob Celestine Aug 22 '18 at 09:42
  • thanks. so I tried your code you put in the post to but the spinner and checkbox beside each other. So I did that but when I ran my app, it was still the spinner above the checkbox, not them side by side... –  Aug 25 '18 at 02:26
  • Do I still have to reinstall app? I will try that –  Aug 25 '18 at 05:39
  • Tried reinstalling the app but still didn't do any difference.. @Jacob Celestine –  Aug 26 '18 at 01:48