I have an XML layout containing a EditText and 2 buttons. If I click on the plus button, a new edittext is programatically added. This works, but the edittext looks different. According to the XML the edittext defined in XML does not have any special attributes, so I believe its not a particular layout setting.
My question is how do I make my programmatically added EditText's look the same?
The EditText's containing the numbers are my programmatically added edittext's. The empty ones are creating in the XML.

(source: tozz.nl)
Code:
LinearLayout baseLayout = (LinearLayout) findViewById(R.id.baseLayout);
LinearLayout linearLayout = new LinearLayout(getApplicationContext());
linearLayout.setId(100 + numPlayers);
linearLayout.setOrientation(LinearLayout.HORIZONTAL);
EditText editText = new EditText(getApplicationContext());
editText.setText(editText.toString().substring(25, 30));
ImageButton delButton = new ImageButton(getApplicationContext());
delButton.setImageResource(R.drawable.ic_delete);
linearLayout.addView(editText);
linearLayout.addView(delButton);
baseLayout.addView(linearLayout);
My XML is as following:
<LinearLayout
android:id="@+id/linearPlayer1"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:orientation="horizontal" >
<EditText
android:id="@+id/editPlayer1"
android:layout_width="0dip"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:layout_weight="1"
android:gravity="center_vertical" />
<ImageButton
android:id="@+id/addPlayer1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="@drawable/ic_input_add" />
</LinearLayout>
Luksprog answered my question:
pass the Activity Context and not the Application Context when creating the new views.
Adding those views with the correct LayoutParams should make the EditText be like the initial one from the layout:
linearLayout.addView(editText, new LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT,
LinearLayout.LayoutParams.WRAP_CONTENT, 1.0f));
linearLayout.addView(delButton, new LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT,
LinearLayout.LayoutParams.WRAP_CONTENT));
baseLayout.addView(linearLayout, new LinearLayout.LayoutParams(LinearLayout.LayoutParams.FILL_PARENT,
LinearLayout.LayoutParams.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