Reputation:
I'm generating EditText
fields and wish to set it's style from styles.xml file. But can't manage to do it. I can set some parameters, but I would rather use a style from styles.xml so it would be easier to change later if needed.
styles.xml
<style name="input_fields_single_line">
<item name="android:padding">8dp</item>
<item name="android:background">@drawable/input_field_shape</item>
<item name="android:maxLines">1</item>
</style>
Java code:
List<EditText> inputFieldList = new ArrayList<EditText>();
public void generateInputFields() {
EditText editTextFieldTitle = new EditText(this);
inputFieldList.add(editTextFieldTitle);
editTextFieldTitle.setHint(R.string.enter_field_title);
editTextFieldTitle.setMaxLines(1);
editTextFieldTitle.setLayoutParams(new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT));
editTextFieldTitle.setFocusableInTouchMode(true);
editTextFieldTitle.requestFocus();
myLayout.addView(editTextFieldTitle);
}
Upvotes: 1
Views: 2841
Reputation: 1
There is a attribute in EditText called styles use that.and if you want to customize it than make own style in drawable , A new XML and link to the editText using styles attribute.
Upvotes: 0
Reputation:
I found the solution here. Android: set view style programmatically
editTextFieldTitle = new EditText(new ContextThemeWrapper(getBaseContext(),R.style.input_fields_single_line),null,0);
Upvotes: 0
Reputation: 2066
You create a separate style for the EditText like what you are doing but parented with the Widget.EditText like the following:
<style name="MyCustomeEditTextStyle" parent="@android:style/Widget.EditText">
...add as many items as you need
<item name="android:padding">8dp</item>
<item name="android:background">@drawable/input_field_shape</item>
<item name="android:maxLines">1</item>
</style>
Then call your style inside each edit text in the xml like the following:
<EditText
android:id="@+id/editTextId"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
style="@style/MyCustomeEditTextStyle" />
BUT if you are want it to be globally set once and set without the xml because you are generating your EditText programmatically like this:
EditText editTextFieldTitle = new EditText(this);
you can then set your style in the application style like this:
<style name="AppTheme" parent="@android:style/YourParentTheme">
<item name="android:editTextStyle">@style/MyCustomeEditTextStyle</item>
</style>
Upvotes: 1