如何使用按钮背景并排创建微调器和复选框

How to create a spinner and a checkbox side by side with a button background

我正在尝试制作我的布局,以便我拥有这两个元素:一个复选框和一个下拉菜单,它们并排放置,并且它有一个类似背景的按钮。

目前,我有我的设计,所以它只是一个在彼此下面的元素,如第二张图片所示。我想要它看起来像:

我希望我的布局看起来像什么

目前的样子::

请注意:假设单词 'flour' 是 Spinner 项(忽略数字 3)

谢谢!

以下是我的 create.java 代码:

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代码如下:

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

使用此方法ViewGroup#addView (View child, int index) 以便您可以指定应添加新子项的位置。

示例:

mLinearLayout.addView(newButton, 0);

我想找到一种方法来在按钮顶部放置下拉菜单和复选框等元素

根据我对此的理解,如果您想要以编程方式并排放置微调器和复选框,请执行以下操作:

第一个变化:

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

至:

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

现在在您的 java 代码中,要使微调器和复选框并排出现,代码如下:

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

我稍微更改了您的布局并在我的 phone 上尝试了这段代码,这是我得到的结果:

Screenshot

再一次,这是我对你的问题的理解。如果这就是您要找的东西,那就太好了!否则,让我们根据这个答案进行更多讨论。