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

时间:2018-08-08 22:59:54

标签: android android-layout android-view

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

当前,我已经设计好了,所以它只是彼此之间的一个元素,如第二幅图所示。我想要它,看起来像:

我希望布局看起来像什么

目前是什么样的:

enter image description here

请注意:假设“面粉”一词是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>

2 个答案:

答案 0 :(得分:0)

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

示例:

mLinearLayout.addView(newButton, 0);

答案 1 :(得分: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);
            }
        });

我稍微改变了布局,并在手机上尝试了此代码,这是我得到的结果:

Screenshot

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