简体   繁体   中英

Set columnWeight on EditText

I'm using a GridLayout in my activity and I used a couple EditText to fill the grid. The width and everything looked good. Now I want to add the EditTexts dynamic to the existing GridLayout. But I have some problems to translate the XML attributes to Java. Especially I don't know how to set the columnWeight correct.

This is the GridLayout:

<GridLayout
                android:id="@+id/cellGrid"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:columnCount="8"
                android:rowCount="5">
...
</GridLayout>

This was one of the correct looking XML EditTexts:

<EditText
                    android:layout_width="20dp"
                    android:layout_height="wrap_content"
                    android:layout_columnWeight="1"
                    android:layout_marginBottom="2dp"
                    android:layout_marginEnd="2dp"
                    android:background="@color/middelGrey"
                    android:inputType="numberDecimal"
                    android:textAlignment="center"
                    android:textSize="12dp" />

And this is how I try to add the EditTexts to the Grid in a for-loop

for(int i=0; i < amountOfCells/2; i++){
        EditText editText = new EditText(getContext());

     editText.setBackgroundColor(getResources().getColor(R.color.middelGrey, null));
        editText.setInputType(InputType.TYPE_NUMBER_FLAG_DECIMAL);

        LinearLayout.LayoutParams llp = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT, 1f);
        llp.setMargins(0, 0, 2, 2);
        editText.setLayoutParams(llp);
        editText.setTextAlignment(View.TEXT_ALIGNMENT_CENTER);
        editText.setWidth(20);
        editText.setHeight(wrap_content);
        gridLayout.addView(editText, i);
    }

But it doesn't look like the xml version, I think the columnWeight is not set correct.

Set following layout parameters instead of yours:

GridLayout.LayoutParams parem = new LayoutParams(GridLayout.spec(GridLayout.UNDEFINED, 1f),  GridLayout.spec(GridLayout.UNDEFINED, 1f));

This can be found here: Link

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM