Here's XML:
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
style="#style/LightStyle"
android:layout_width="fill_parent"
android:layout_height="55dip"
android:clickable="true"
android:orientation="horizontal" >
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="horizontal" />
</RelativeLayout>
How to set style attribute programmatically?
Technically you can apply styles programmatically, with custom views anyway:
private MyRelativeLayout extends RelativeLayout {
public MyRelativeLayout(Context context) {
super(context, null, R.style.LightStyle);
}
}
The one argument constructor is the one used when you instantiate views programmatically.
So chain this constructor to the super that takes a style parameter.
RelativeLayout someLayout = new MyRelativeLayout(new ContextThemeWrapper(this,R.style.RadioButton));
Or as #Dori pointed out simply:
RelativeLayout someLayout = new RelativeLayout(new ContextThemeWrapper(activity,R.style.LightStyle));
Now in Kotlin:
class MyRelativeLayout #JvmOverloads constructor(
context: Context,
attributeSet: AttributeSet? = null,
defStyleAttr: Int = R.style.LightStyle,
) : RelativeLayout(context, attributeSet, defStyleAttr)
or
val rl = RelativeLayout(ContextThemeWrapper(activity, R.style.LightStyle))
What worked for me:
Button b = new Button(new ContextThemeWrapper(this, R.style.ButtonText), null, 0);
Use a ContextThemeWrapper
AND
Use the 3-arguments constructor (won't work without this)
Update: At the time of answering this question (mid 2012, API level 14-15), setting the view programmatically was not an option (even though there were some non-trivial workarounds) whereas this has been made possible after the more recent API releases. See #Blundell's answer for details.
OLD Answer:
You cannot set a view's style programmatically yet, but you may find this thread useful.
For a new Button/TextView:
Button mMyButton = new Button(new ContextThemeWrapper(this, R.style.button_disabled), null, 0);
For an existing instance:
mMyButton.setTextAppearance(this, R.style.button_enabled);
For Image or layouts:
Image mMyImage = new ImageView(new ContextThemeWrapper(context, R.style.article_image), null, 0);
This is quite old question but solution that worked for me now is to use 4th parameter of constructor defStyleRes - if available.. on view... to set style
Following works for my purposes (kotlin):
val textView = TextView(context, null, 0, R.style.Headline1)
If you'd like to continue using XML (which the accepted answer doesn't let you do) and set the style after the view has been created you may be able to use the Paris library which supports a subset of all available attributes.
Since you're inflating your view from XML you'd need to specify an id in the layout:
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/my_styleable_relative_layout"
style="#style/LightStyle"
...
Then when you need to change the style programmatically, after the layout has been inflated:
// Any way to get the view instance will do
RelativeLayout myView = findViewById(R.id.my_styleable_relative_layout);
// This will apply all the supported attribute values of the style
Paris.style(myView).apply(R.style.LightStyle);
For more: the list of supported view types and attributes (includes background, padding, margin, etc. and can easily be extended) and installation instructions with additional documentation.
Disclaimer: I'm the original author of said library.
You can apply a style to your activity by doing:
super.setTheme( R.style.MyAppTheme );
or Android default:
super.setTheme( android.R.style.Theme );
in your activity, before setContentView().
Non of the provided answers are correct.
You CAN set style programatically.
Short answer is take a look at http://grepcode.com/file/repository.grepcode.com/java/ext/com.google.android/android/5.1.1_r1/android/content/Context.java#435
Long answer.
Here's my snippet to set custom defined style programatically to your view:
1) Create a style in your styles.xml file
<style name="MyStyle">
<item name="customTextColor">#39445B</item>
<item name="customDividerColor">#8D5AA8</item>
</style>
Do not forget to define your custom attributes in attrs.xml file
My attrsl.xml file:
<declare-styleable name="CustomWidget">
<attr name="customTextColor" format="color" />
<attr name="customDividerColor" format="color" />
</declare-styleable>
Notice you can use any name for your styleable (my CustomWidget)
Now lets set the style to the widget Programatically
Here's My simple widget:
public class StyleableWidget extends LinearLayout {
private final StyleLoader styleLoader = new StyleLoader();
private TextView textView;
private View divider;
public StyleableWidget(Context context) {
super(context);
init();
}
private void init() {
inflate(getContext(), R.layout.widget_styleable, this);
textView = (TextView) findViewById(R.id.text_view);
divider = findViewById(R.id.divider);
setOrientation(VERTICAL);
}
protected void apply(StyleLoader.StyleAttrs styleAttrs) {
textView.setTextColor(styleAttrs.textColor);
divider.setBackgroundColor(styleAttrs.dividerColor);
}
public void setStyle(#StyleRes int style) {
apply(styleLoader.load(getContext(), style));
}
}
layout:
<TextView
android:id="#+id/text_view"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textSize="22sp"
android:layout_gravity="center"
android:text="#string/styleble_title" />
<View
android:id="#+id/divider"
android:layout_width="match_parent"
android:layout_height="1dp"/>
</merge>
And finally StyleLoader class implementation
public class StyleLoader {
public StyleLoader() {
}
public static class StyleAttrs {
public int textColor;
public int dividerColor;
}
public StyleAttrs load(Context context, #StyleRes int styleResId) {
final TypedArray styledAttributes = context.obtainStyledAttributes(styleResId, R.styleable.CustomWidget);
return load(styledAttributes);
}
#NonNull
private StyleAttrs load(TypedArray styledAttributes) {
StyleAttrs styleAttrs = new StyleAttrs();
try {
styleAttrs.textColor = styledAttributes.getColor(R.styleable.CustomWidget_customTextColor, 0);
styleAttrs.dividerColor = styledAttributes.getColor(R.styleable.CustomWidget_customDividerColor, 0);
} finally {
styledAttributes.recycle();
}
return styleAttrs;
}
}
You can find fully working example at https://github.com/Defuera/SetStylableProgramatically
This is my simple example, the key is the ContextThemeWrapper wrapper, without it, my style does not work, and using the three parameters constructor of the View.
ContextThemeWrapper themeContext = new ContextThemeWrapper(this, R.style.DefaultLabelStyle);
TextView tv = new TextView(themeContext, null, 0);
tv.setText("blah blah ...");
layout.addView(tv);
the simple way is passing through constructor
RadioButton radioButton = new RadioButton(this,null,R.style.radiobutton_material_quiz);
I don't propose to use ContextThemeWrapper as it do this:
The specified theme will be applied on top of
the base context's theme.
What can make unwanted results in your application. Instead I propose new library "paris" for this from engineers at Airbnb:
https://github.com/airbnb/paris
Define and apply styles to Android views programmatically.
But after some time of using it I found out it's actually quite limited and I stopped using it because it does not support a lot of properties i need out off the box, so one have to check out and decide as always.
int buttonStyle = R.style.your_button_style;
Button button = new Button(new ContextThemeWrapper(context, buttonStyle), null, buttonStyle);
Only this answer works for me. See https://stackoverflow.com/a/24438579/5093308
best simple solution i found, using alertDialog with a custom layout, is :
val mView = LayoutInflater.from(context).inflate(layoutResId, null)
val dialog = AlertDialog.Builder(context, R.style.CustomAlertDialog)
.setView(mView)
.setCancelable(false)
.create()
where style is
<style name="CustomAlertDialog" parent="Theme.AppCompat.Light.Dialog.Alert">
<item name="android:background">#drawable/bg_dialog_white_rounded</item>
</style>
and bg_dialog_white_rounded.xml is
<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android">
<corners android:radius="16dp" />
<solid android:color="#Color/white" />
</shape>
layoutResId is a resource id of any layout that has to have the theme set to "#style/CustomAlertDialog", for example:
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.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:id="#+id/root"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_marginStart="#dimen/wdd_margin_medium"
android:theme="#style/CustomAlertDialog"
android:layout_marginEnd="#dimen/wdd_margin_medium">
..... etc...
</androidx.constraintlayout.widget.ConstraintLayout>
I used views defined in XML in my composite ViewGroup, inflated them added to Viewgroup. This way I cannot dynamically change style but I can make some style customizations. My composite:
public class CalendarView extends LinearLayout {
private GridView mCalendarGrid;
private LinearLayout mActiveCalendars;
private CalendarAdapter calendarAdapter;
public CalendarView(Context context) {
super(context);
}
public CalendarView(Context context, AttributeSet attrs) {
super(context, attrs);
}
#Override
protected void onFinishInflate() {
super.onFinishInflate();
init();
}
private void init() {
mCalendarGrid = (GridView) findViewById(R.id.calendarContents);
mCalendarGrid.setNumColumns(CalendarAdapter.NUM_COLS);
calendarAdapter = new CalendarAdapter(getContext());
mCalendarGrid.setAdapter(calendarAdapter);
mActiveCalendars = (LinearLayout) findViewById(R.id.calendarFooter);
}
}
and my view in xml where i can assign styles:
<com.mfitbs.android.calendar.CalendarView
xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/calendar"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_gravity="center_horizontal"
android:orientation="vertical"
>
<GridView
android:id="#+id/calendarContents"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
<LinearLayout
android:id="#+id/calendarFooter"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal"
/>
if inside own custom view :
val editText = TextInputEditText(context, attrs, defStyleAttr)
You can create the xml containing the layout with the desired style and then change the background resource of your view, like this.
Related
I created a custom input method that changes layouts dynamically. I want to align the last view to the bottom of the input area. I set the layout_alignParentBottom property for the last view, but then the input area expands to fill almost the entire screen, as seen here.
Without layout_alignParentBottom set
With layout_alignParentBottom set
I do have an android:windowBackground style set, but even without it, it does the same thing. I inflate my XML layout in my custom InputMethodService class in onCreateInputView(), and I don't adjust any layout settings in the onFinishInflate() method of MyClass. Here is my code. Any ideas?
my_class_layout.xml
<?xml version="1.0" encoding="utf-8"?>
<com.package.MyClass xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content" >
<Button
android:id="#+id/login_button"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:layout_marginLeft="10dp"
android:layout_marginRight="10dp"
android:layout_marginBottom="10dp"
android:text="#string/login" />
</com.package.MyClass>
MyClass.java
package com.package;
<imports>
public class MyClass extends RelativeLayout {
private final MyClassInputMethodService mInputMethodServiceContext;
private Button mLoginButton;
public MyClass(Context context, AttributeSet attrs) {
super(context, attrs);
mInputMethodServiceContext = (MyClassInputMethodService)context;
}
public MyClass( MyClassInputMethodService context ) {
super(context);
mInputMethodServiceContext = (MyClassInputMethodService)context;
}
#Override
protected void onFinishInflate() {
// Login button
mLoginButton = (Button)findViewById(R.id.login_button);
}
MyClassInputMethodService.java
package com.package;
<imports>
public class MyClassInputMethodService extends InputMethodService {
private static final String TAG = MyClassInputMethodService.class.getSimpleName();
private static MyClassInputMethodService mContext;
private View mInputView;
#Override
public void onCreate() {
// Set Theme
setTheme(UserManagement.getCurrentUser().getTheme().getResourceId());
super.onCreate();
mContext = this;
}
#Override
public View onCreateInputView() {
mInputView = (MyClassLogin) getLayoutInflater().inflate(R.layout.fast_fill_login, null);
return mInputView;
}
}
EDIT
I tried a smaller-sized image for the windowBackground drawable, and it did make the default input method area smaller.
<style name="Theme.Blue" >
<item name="android:windowBackground">#drawable/background_blue</item>
</style>
So that leads me to another possibility. Do I have to use the smallest possible background image size that would fit the least number of views that will be shown, or can I make the windowBackground drawable dynamic, so it will only use as much height as the input method views use?
I using custom switch for support of API 8. I am using THIS Libarary for Custom Switch. But I want to make something Like show in figure.I have tried to change the color ,though changing the color in the style but doesn't effect as i want.
Please help me , Thanks in advance.
Here's a full, working solution, after a fun day implementing this.
Use the following to set the drawable for the track of the switch. The track is the container within which the thumb slides left and right.
mMessengerSwitch.setTrackDrawable(new SwitchTrackTextDrawable(this,
"LEFT", "RIGHT"));
Here's the implementation of the SwitchTrackTextDrawable, which writes the text in the background exactly in the right position (well, I've only tested it for API 23 on a Nexus 5):
/**
* Drawable that generates the two pieces of text in the track of the switch, one of each
* side of the positions of the thumb.
*/
public class SwitchTrackTextDrawable extends Drawable {
private final Context mContext;
private final String mLeftText;
private final String mRightText;
private final Paint mTextPaint;
public SwitchTrackTextDrawable(#NonNull Context context,
#StringRes int leftTextId,
#StringRes int rightTextId) {
mContext = context;
// Left text
mLeftText = context.getString(leftTextId);
mTextPaint = createTextPaint();
// Right text
mRightText = context.getString(rightTextId);
}
private Paint createTextPaint() {
Paint textPaint = new Paint();
//noinspection deprecation
textPaint.setColor(mContext.getResources().getColor(android.R.color.white));
textPaint.setAntiAlias(true);
textPaint.setStyle(Paint.Style.FILL);
textPaint.setTextAlign(Paint.Align.CENTER);
// Set textSize, typeface, etc, as you wish
return textPaint;
}
#Override
public void draw(Canvas canvas) {
final Rect textBounds = new Rect();
mTextPaint.getTextBounds(mRightText, 0, mRightText.length(), textBounds);
// The baseline for the text: centered, including the height of the text itself
final int heightBaseline = canvas.getClipBounds().height() / 2 + textBounds.height() / 2;
// This is one quarter of the full width, to measure the centers of the texts
final int widthQuarter = canvas.getClipBounds().width() / 4;
canvas.drawText(mLeftText, 0, mLeftText.length(),
widthQuarter, heightBaseline,
mTextPaint);
canvas.drawText(mRightText, 0, mRightText.length(),
widthQuarter * 3, heightBaseline,
mTextPaint);
}
#Override
public void setAlpha(int alpha) {
}
#Override
public void setColorFilter(ColorFilter cf) {
}
#Override
public int getOpacity() {
return PixelFormat.TRANSLUCENT;
}
}
Try using
android:textOn="On"
android:textOff="Off"
instead of
android:text="On"
in switches.
You can also go through this if it helps.
After struggling to find the right solution for this, I found this neat little library. I found it easy to use and it met my needs perfectly. It can even be used to display more than 2 values.
UPDATE: In the meanwhile this library has stopped being maintained, so you may want to try the one they recommend.
This is how I made it look eventually with some more styling, like white border which I put around a FrameLayout that wraps it (I needed to make it look exactly like this, you need not use border):
Here's the xml for this:
<FrameLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:padding="1dp"
android:background="#drawable/white_border">
<belka.us.androidtoggleswitch.widgets.ToggleSwitch
android:layout_width="wrap_content"
android:layout_height="wrap_content"
custom:activeBgColor="#color/white"
custom:activeTextColor="#color/black"
custom:inactiveBgColor="#color/black"
custom:inactiveTextColor="#color/white"
custom:textToggleLeft="left"
custom:textToggleRight="right"/>
</FrameLayout>
And #drawable/white_border looks like this:
<shape xmlns:android="http://schemas.android.com/apk/res/android" android:shape="rectangle" >
<solid android:color="#android:color/transparent" />
<stroke android:width="2dip"
android:color="#color/white" />
<corners
android:radius="3dp"/>
I created a custom layout that contain a linear layout (will be used as a track of the switch) in this layout I placed two texts to simulate the track "on"/"off" texts, and on top of it, it has a regular switch but without a track, just a thumb with transparent track.
Anyway this is the code:
colors.xml
<color name="switch_selected_text_color">#FFFFFF</color>
<color name="switch_regular_text_color">#A8A8A8</color>
settings_switch_color_selector
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:color="#color/switch_selected_text_color" android:state_checked="true" />
<item android:color="#color/switch_regular_text_color" />
</selector>
styles.xml
<style name="SwitchTextAppearance" parent="#android:style/TextAppearance.Holo.Small">
<item name="android:textColor">#color/settings_switch_color_selector</item>
</style>
new_switch.xml - used in the custom view
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="wrap_content"
android:layout_height="wrap_content">
<LinearLayout
android:id="#+id/track_layout"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:background="#drawable/settings_track"
android:weightSum="1">
<TextView
android:id="#+id/left_text"
android:layout_width="0dp"
android:layout_height="match_parent"
android:textColor="#color/switch_regular_text_color"
android:layout_weight="0.5"
android:gravity="center"
android:text="OFF" />
<TextView
android:id="#+id/right_text"
android:layout_width="0dp"
android:layout_height="match_parent"
android:textColor="#color/switch_regular_text_color"
android:layout_weight="0.5"
android:gravity="center"
android:text="ON" />
</LinearLayout>
<Switch
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:thumb="#drawable/thumb_selector"
android:switchTextAppearance="#style/SwitchTextAppearance"
android:textOn="ON"
android:textOff="OFF"
android:checked="true"
android:showText="true"
android:track="#android:color/transparent"/>
</RelativeLayout>
this is custom view - it`s just for inflating the custom view layout
public class DoubleSidedSwitch extends RelativeLayout {
private TextView _leftTextView;
private TextView _rightTextView;
private Switch _switch;
public DoubleSidedSwitch(Context context) {
super(context);
init(context);
}
public DoubleSidedSwitch(Context context, AttributeSet attrs) {
super(context, attrs);
init(context);
}
private void init(Context context) {
View view = LayoutInflater.from(context).inflate(R.layout.new_switch, this, true);
initViews(view);
initListeners();
}
private void initListeners() {
}
private void initViews(View view) {
}
}
There is one made by 2 Standard buttons and a LinearLayout. There are bunch of xml files to import but it works perfect on all versions and very easy to use. Check the following Github Page
Custom Switch With 2 Buttons
usage
Copy XML files under res/drawable to your project's res/drawable folder.
Copy LinearLayout from layout.xml to your layout file.
Copy values from values/colors.xml and values/dimens to your own files.
Initilize the switch with following code
SekizbitSwitch mySwitch = new SekizbitSwitch(findViewById(R.id.sekizbit_switch));
mySwitch.setOnChangeListener(new SekizbitSwitch.OnSelectedChangeListener() {
#Override
public void OnSelectedChange(SekizbitSwitch sender) {
if(sender.getCheckedIndex() ==0 )
{
System.out.println("Left Button Selected");
}
else if(sender.getCheckedIndex() ==1 )
{
System.out.println("Right Button Selected");
}
}
});
I implemented a DialogPreference exactly the way it is explained in http://www.lukehorvat.com/blog/android-seekbardialogpreference
Additionally I was able to change the text- and divider color of the DialogPreference, but I couldn't change the highlighting color of the buttons when they are pressed. Does anybody know how to do this?
Update:
I use the following layout for the DialogPreference:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<TextView
android:id="#+id/text_dialog_message"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="6dip"
android:paddingLeft="12dip"
android:paddingRight="12dip"/>
<TextView
android:id="#+id/text_progress"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="6dip"
android:gravity="center_horizontal"/>
<SeekBar
android:id="#+id/seek_bar"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginBottom="6dip"
android:layout_marginTop="6dip"/>
</LinearLayout>
The only style attributes regarding this DialogPreference or the layout I change so far are changed programatically:
int alertTitleId = this.getContext().getResources().getIdentifier("alertTitle", "id", "android");
TextView alertTitle = (TextView) getDialog().getWindow().getDecorView().findViewById(alertTitleId);
alertTitle.setTextColor(color); // change title text color
int titleDividerId = this.getContext().getResources().getIdentifier("titleDivider", "id", "android");
View titleDivider = getDialog().getWindow().getDecorView().findViewById(titleDividerId);
titleDivider.setBackgroundColor(color); // change divider color
All you need to do is subclass DialogPreference, then call Resource.getIdentifier to locate each View you want to theme, much like you're doing, but you don't need to call Window.getDecorView. Here's an example:
Custom DialogPreference
public class CustomDialogPreference extends DialogPreference {
public CustomDialogPreference(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
}
public CustomDialogPreference(Context context, AttributeSet attrs) {
super(context, attrs);
}
/**
* {#inheritDoc}
*/
#Override
protected void showDialog(Bundle state) {
super.showDialog(state);
final Resources res = getContext().getResources();
final Window window = getDialog().getWindow();
final int green = res.getColor(android.R.color.holo_green_dark);
// Title
final int titleId = res.getIdentifier("alertTitle", "id", "android");
final View title = window.findViewById(titleId);
if (title != null) {
((TextView) title).setTextColor(green);
}
// Title divider
final int titleDividerId = res.getIdentifier("titleDivider", "id", "android");
final View titleDivider = window.findViewById(titleDividerId);
if (titleDivider != null) {
titleDivider.setBackgroundColor(green);
}
// Button views
window.findViewById(res.getIdentifier("button1", "id", "android"))
.setBackgroundDrawable(res.getDrawable(R.drawable.your_selector));
window.findViewById(res.getIdentifier("button2", "id", "android"))
.setBackgroundDrawable(res.getDrawable(R.drawable.your_selector));
window.findViewById(res.getIdentifier("button3", "id", "android"))
.setBackgroundDrawable(res.getDrawable(R.drawable.your_selector));
}
}
XML preferences
<PreferenceScreen xmlns:android="http://schemas.android.com/apk/res/android" >
<path_to.CustomDialogPreference
android:dialogMessage="Message"
android:negativeButtonText="Cancel"
android:positiveButtonText="Okay"
android:title="Title" />
</PreferenceScreen>
Custom selector
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android" android:autoMirrored="true">
<item android:drawable="#drawable/your_pressed_drawable" android:state_pressed="true"/>
<item android:drawable="#drawable/your_default_drawable"/>
</selector>
Alternate selector
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android" android:autoMirrored="true">
<item android:drawable="#color/your_pressed_color" android:state_pressed="true"/>
<item android:drawable="#color/your_default_color/>
</selector>
Screenshot
If you fail to find a solution for styling the built-in buttons to your liking, you could actually add a button row to the bottom of your custom layout, which looks and acts exactly like the built-in one. Then set your button listeners to your custom button bar's buttons, which will result in no built-in button bar.
In this way you can make them look however you want!
I you can try this Answer. Here you don't need write code just need customise AlertDialog theme.
After customisation theme it may be applicable for your complete application.
I have a custom Table Row that I am in the process of making. I want to use an XML file to define what a single row looks like. I would like to have a class extend TableRow and define itself to be the file as defined in the XML. The XML file might look like:
<TableRow xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="horizontal" >
<TextView
android:id="#+id/label"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:paddingRight="10dp"
android:text="#string/loading"
android:textAppearance="?android:attr/textAppearanceLarge" />
<TextView
android:id="#+id/data"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:gravity="right"
android:text="#string/loading"
android:textAppearance="?android:attr/textAppearanceLarge" />
</TableRow>
And the code might look like:
public class SpecialTableRow extends TableRow {
public SpecialTableRow (Context context) {
}
}
Is there something that I can put into the constructor to have the class assume it is the tableRow in it's entirety? Alternatively, is there another structure which would work better? The best that I've figured out is this:
TableRow tr=(TableRow) LayoutInflater.from(context).inflate(R.layout.text_pair,null);
TextView mFieldName=(TextView) tr.findViewById(R.id.label);
TextView mValue=(TextView) tr.findViewById(R.id.data);
tr.removeAllViewsInLayout();
addView(mFieldName);
addView(mValue);
But this removes the layout parameters from the XML. Anything better out there?
Take a look at the tutorial on creating custom views. You will want to subclass TableRow and add the additional views you want to display. Then, you can use your new view directly in your XML layouts and additionally create any custom attributes you might want. I've included an example which creates a custom TableRow named TextPairRow, inflates a layout with two TextViews to show within the TableRow and adds showLabel and showData custom attributes which show/hide the two TextViews. Finally, I've included how you would use your new view directly in your XML layouts.
class TextPairRow extends TableRow {
private TextView label, data;
public TextPairRow (Context context, AttributeSet attrs) {
super(context, attrs);
TypedArray a = context.getTheme().obtainStyledAttributes(
attrs,
R.styleable.TextPairRow, 0, 0);
try {
showLabel = a.getBoolean(R.styleable.TextPairRow_showLabel, false);
showData = a.getBoolean(R.styleable.TextPairRow_showData, false);
} finally {
a.recycle();
}
initViews();
}
private void initViews(){
// Here you can inflate whatever you want to be in your
// view or add views programatically.
// In this example, we'll just assume you have a basic XML
// layout which defines a LinearLayout with two TextViews.
LinearLayout mLayout = (LinearLayout)
LayoutInflater.from(getContext()).inflate(R.layout.textview_layout, this);
label = (TextView) mLayout.findViewById(R.id.label);
data = (TextView) mLayout.findViewById(R.id.data);
if(showLabel)
label.setVisibility(View.VISIBLE);
else
label.setVisibility(View.GONE); // can also use View.INVISIBLE
// depending on your needs
if(showData){
data.setVisibility(View.VISIBLE);
else
data.setVisibility(View.GONE); // can also use View.INVISIBLE
// depending on your needs
}
}
This is where you define your custom XML attributes (locate or create this file: res/values/attrs.xml)
<resources>
<declare-styleable name="TextPairRow">
<attr name="showText" format="boolean" />
<attr name="showLabel" format="boolean" />
</declare-styleable>
</resources>
Finally, to use your new view directly in your XML layouts:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:custom="http://schemas.android.com/apk/res-auto">
<com.thefull.packageforyourview.TextPairRow
android:orientation="horizontal"
custom:showData="true"
custom:showLabel="true" />
</LinearLayout>
Note that you might need to use xmlns:custom="http://schemas.android.com/apk/res/com.thefull.packageforyourview" depending on if your custom view will be in a library project. Regardless, either this or what's in the example will work.
The real trick to doing this is actually quite simple. Use the second parameter of the inflate method. In fact, the best thing to do is this:
LayoutInflater.from(context).inflate(R.layout.text_pair,this);
This will inflate the R.layout.text_pair into this, effectively using the entire row. No need to add the view manually, Android takes care of it for you.
The only thing I can think of is to use a static method instead of constructor. For example:
public static void newInstance (Context context) {
this = context.getLayoutInflater().inflate(R.layout.text_pair, null, null);
}
Then don't use constructor for initializing an object, call this method.
Here's XML:
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
style="#style/LightStyle"
android:layout_width="fill_parent"
android:layout_height="55dip"
android:clickable="true"
android:orientation="horizontal" >
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="horizontal" />
</RelativeLayout>
How to set style attribute programmatically?
Technically you can apply styles programmatically, with custom views anyway:
private MyRelativeLayout extends RelativeLayout {
public MyRelativeLayout(Context context) {
super(context, null, R.style.LightStyle);
}
}
The one argument constructor is the one used when you instantiate views programmatically.
So chain this constructor to the super that takes a style parameter.
RelativeLayout someLayout = new MyRelativeLayout(new ContextThemeWrapper(this,R.style.RadioButton));
Or as #Dori pointed out simply:
RelativeLayout someLayout = new RelativeLayout(new ContextThemeWrapper(activity,R.style.LightStyle));
Now in Kotlin:
class MyRelativeLayout #JvmOverloads constructor(
context: Context,
attributeSet: AttributeSet? = null,
defStyleAttr: Int = R.style.LightStyle,
) : RelativeLayout(context, attributeSet, defStyleAttr)
or
val rl = RelativeLayout(ContextThemeWrapper(activity, R.style.LightStyle))
What worked for me:
Button b = new Button(new ContextThemeWrapper(this, R.style.ButtonText), null, 0);
Use a ContextThemeWrapper
AND
Use the 3-arguments constructor (won't work without this)
Update: At the time of answering this question (mid 2012, API level 14-15), setting the view programmatically was not an option (even though there were some non-trivial workarounds) whereas this has been made possible after the more recent API releases. See #Blundell's answer for details.
OLD Answer:
You cannot set a view's style programmatically yet, but you may find this thread useful.
For a new Button/TextView:
Button mMyButton = new Button(new ContextThemeWrapper(this, R.style.button_disabled), null, 0);
For an existing instance:
mMyButton.setTextAppearance(this, R.style.button_enabled);
For Image or layouts:
Image mMyImage = new ImageView(new ContextThemeWrapper(context, R.style.article_image), null, 0);
This is quite old question but solution that worked for me now is to use 4th parameter of constructor defStyleRes - if available.. on view... to set style
Following works for my purposes (kotlin):
val textView = TextView(context, null, 0, R.style.Headline1)
If you'd like to continue using XML (which the accepted answer doesn't let you do) and set the style after the view has been created you may be able to use the Paris library which supports a subset of all available attributes.
Since you're inflating your view from XML you'd need to specify an id in the layout:
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/my_styleable_relative_layout"
style="#style/LightStyle"
...
Then when you need to change the style programmatically, after the layout has been inflated:
// Any way to get the view instance will do
RelativeLayout myView = findViewById(R.id.my_styleable_relative_layout);
// This will apply all the supported attribute values of the style
Paris.style(myView).apply(R.style.LightStyle);
For more: the list of supported view types and attributes (includes background, padding, margin, etc. and can easily be extended) and installation instructions with additional documentation.
Disclaimer: I'm the original author of said library.
You can apply a style to your activity by doing:
super.setTheme( R.style.MyAppTheme );
or Android default:
super.setTheme( android.R.style.Theme );
in your activity, before setContentView().
Non of the provided answers are correct.
You CAN set style programatically.
Short answer is take a look at http://grepcode.com/file/repository.grepcode.com/java/ext/com.google.android/android/5.1.1_r1/android/content/Context.java#435
Long answer.
Here's my snippet to set custom defined style programatically to your view:
1) Create a style in your styles.xml file
<style name="MyStyle">
<item name="customTextColor">#39445B</item>
<item name="customDividerColor">#8D5AA8</item>
</style>
Do not forget to define your custom attributes in attrs.xml file
My attrsl.xml file:
<declare-styleable name="CustomWidget">
<attr name="customTextColor" format="color" />
<attr name="customDividerColor" format="color" />
</declare-styleable>
Notice you can use any name for your styleable (my CustomWidget)
Now lets set the style to the widget Programatically
Here's My simple widget:
public class StyleableWidget extends LinearLayout {
private final StyleLoader styleLoader = new StyleLoader();
private TextView textView;
private View divider;
public StyleableWidget(Context context) {
super(context);
init();
}
private void init() {
inflate(getContext(), R.layout.widget_styleable, this);
textView = (TextView) findViewById(R.id.text_view);
divider = findViewById(R.id.divider);
setOrientation(VERTICAL);
}
protected void apply(StyleLoader.StyleAttrs styleAttrs) {
textView.setTextColor(styleAttrs.textColor);
divider.setBackgroundColor(styleAttrs.dividerColor);
}
public void setStyle(#StyleRes int style) {
apply(styleLoader.load(getContext(), style));
}
}
layout:
<TextView
android:id="#+id/text_view"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textSize="22sp"
android:layout_gravity="center"
android:text="#string/styleble_title" />
<View
android:id="#+id/divider"
android:layout_width="match_parent"
android:layout_height="1dp"/>
</merge>
And finally StyleLoader class implementation
public class StyleLoader {
public StyleLoader() {
}
public static class StyleAttrs {
public int textColor;
public int dividerColor;
}
public StyleAttrs load(Context context, #StyleRes int styleResId) {
final TypedArray styledAttributes = context.obtainStyledAttributes(styleResId, R.styleable.CustomWidget);
return load(styledAttributes);
}
#NonNull
private StyleAttrs load(TypedArray styledAttributes) {
StyleAttrs styleAttrs = new StyleAttrs();
try {
styleAttrs.textColor = styledAttributes.getColor(R.styleable.CustomWidget_customTextColor, 0);
styleAttrs.dividerColor = styledAttributes.getColor(R.styleable.CustomWidget_customDividerColor, 0);
} finally {
styledAttributes.recycle();
}
return styleAttrs;
}
}
You can find fully working example at https://github.com/Defuera/SetStylableProgramatically
This is my simple example, the key is the ContextThemeWrapper wrapper, without it, my style does not work, and using the three parameters constructor of the View.
ContextThemeWrapper themeContext = new ContextThemeWrapper(this, R.style.DefaultLabelStyle);
TextView tv = new TextView(themeContext, null, 0);
tv.setText("blah blah ...");
layout.addView(tv);
the simple way is passing through constructor
RadioButton radioButton = new RadioButton(this,null,R.style.radiobutton_material_quiz);
I don't propose to use ContextThemeWrapper as it do this:
The specified theme will be applied on top of
the base context's theme.
What can make unwanted results in your application. Instead I propose new library "paris" for this from engineers at Airbnb:
https://github.com/airbnb/paris
Define and apply styles to Android views programmatically.
But after some time of using it I found out it's actually quite limited and I stopped using it because it does not support a lot of properties i need out off the box, so one have to check out and decide as always.
int buttonStyle = R.style.your_button_style;
Button button = new Button(new ContextThemeWrapper(context, buttonStyle), null, buttonStyle);
Only this answer works for me. See https://stackoverflow.com/a/24438579/5093308
best simple solution i found, using alertDialog with a custom layout, is :
val mView = LayoutInflater.from(context).inflate(layoutResId, null)
val dialog = AlertDialog.Builder(context, R.style.CustomAlertDialog)
.setView(mView)
.setCancelable(false)
.create()
where style is
<style name="CustomAlertDialog" parent="Theme.AppCompat.Light.Dialog.Alert">
<item name="android:background">#drawable/bg_dialog_white_rounded</item>
</style>
and bg_dialog_white_rounded.xml is
<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android">
<corners android:radius="16dp" />
<solid android:color="#Color/white" />
</shape>
layoutResId is a resource id of any layout that has to have the theme set to "#style/CustomAlertDialog", for example:
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.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:id="#+id/root"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_marginStart="#dimen/wdd_margin_medium"
android:theme="#style/CustomAlertDialog"
android:layout_marginEnd="#dimen/wdd_margin_medium">
..... etc...
</androidx.constraintlayout.widget.ConstraintLayout>
I used views defined in XML in my composite ViewGroup, inflated them added to Viewgroup. This way I cannot dynamically change style but I can make some style customizations. My composite:
public class CalendarView extends LinearLayout {
private GridView mCalendarGrid;
private LinearLayout mActiveCalendars;
private CalendarAdapter calendarAdapter;
public CalendarView(Context context) {
super(context);
}
public CalendarView(Context context, AttributeSet attrs) {
super(context, attrs);
}
#Override
protected void onFinishInflate() {
super.onFinishInflate();
init();
}
private void init() {
mCalendarGrid = (GridView) findViewById(R.id.calendarContents);
mCalendarGrid.setNumColumns(CalendarAdapter.NUM_COLS);
calendarAdapter = new CalendarAdapter(getContext());
mCalendarGrid.setAdapter(calendarAdapter);
mActiveCalendars = (LinearLayout) findViewById(R.id.calendarFooter);
}
}
and my view in xml where i can assign styles:
<com.mfitbs.android.calendar.CalendarView
xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/calendar"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_gravity="center_horizontal"
android:orientation="vertical"
>
<GridView
android:id="#+id/calendarContents"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
<LinearLayout
android:id="#+id/calendarFooter"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal"
/>
if inside own custom view :
val editText = TextInputEditText(context, attrs, defStyleAttr)
You can create the xml containing the layout with the desired style and then change the background resource of your view, like this.