I want to create an input box with a submit button to the right. Between them they should span the width of the screen. Currently I have:
LinearLayout row= new LinearLayout(context);
row.setOrientation(HORIZONTAL);
row.setGravity(Gravity.RIGHT);
EditText input = new EditText(context);
Button submit = new Button(context);
submit.setText("Submit");
row.addView(submit);
row.addView(input,LayoutParams.FILL_PARENT,LayoutParams.WRAP_CONTENT);
myView.addView(row,LayoutParams.FILL_PARENT,LayoutParams.WRAP_CONTENT);
This results in the correct distribution of space: The submit button taking up as much space as it needs, the input button taking up the remaining space, however they are the wrong way round (the submit button is on the left, despite setting the gravity). If I take away the gravity, and reverse the order of adding the elements to the row, the input box takes up the whole width of the screen, and the submit button is not visible. What am I doing wrong?
LinearLayout : is a ViewGroup that aligns all children in a single direction, vertically or horizontally. RelativeLayout : is a ViewGroup that displays child views in relative positions. AbsoluteLayout : allows us to specify the exact location of the child views and widgets.
To create a linear layout in which each child uses the same amount of space on the screen, set the android:layout_height of each view to "0dp" (for a vertical layout) or the android:layout_width of each view to "0dp" (for a horizontal layout). Then set the android:layout_weight of each view to "1" .
LinearLayout is less used as compared to RelativeLayout. RelativeLayout is used more in applications. We can use LinearLayout inside RelativeLayout. We can also use RelativeLayout as a Child of LinearLayout.
I'd say it is better to use relative layout and place input to left of the button. But if you really need this with Linear layout you can just use weight parameter:
LinearLayout row= new LinearLayout(context);
EditText input = new EditText(context);
Button submit = new Button(context);
submit.setText("Submit");
LayoutParams inputParams = new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
inputParams.weight = 1;
row.addView(input,inputParams);
LayoutParams buttonParams = new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
buttonParams.weight = 0;
row.addView(submit, buttonParams);
Try adding EditText
first setting its width to fill parent
and its weight to 1, then the button (width = wrap content
)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With