Setting button tint on radio button programmatically - android

I want to set a radio button tint programmatically. in xml there is an attribute called "buttonTint" to do the work. but in program I am not able to find any method to set tint or color to the radio button. is there any method or any ways to do that?
<RadioButton
android:buttonTint="#color/colorPrimaryDark"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Payeer" />

You can use setButtonTintList (ColorStateList tint)
Applies a tint to the button drawable. Does not modify the current tint mode, which is SRC_IN by default.
Subsequent calls to setButtonDrawable(Drawable) will automatically mutate the drawable and apply the specified tint and tint mode using setTintList(ColorStateList).
SAMPLE CODE
public class MainActivity extends AppCompatActivity {
RadioButton radioButton;
#SuppressLint("NewApi")
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
radioButton = findViewById(R.id.radioButton);
ColorStateList myColorStateList = new ColorStateList(
new int[][]{
new int[]{getResources().getColor(R.color.colorPrimaryDark)}
},
new int[]{getResources().getColor(R.color.colorAccent)}
);
radioButton.setButtonTintList(myColorStateList);
}
}

Based on both previous answer one line code for setting background color is
Java code
button.setButtonTintList(ColorStateList.valueOf(getColor(R.color.red)));
Kotlin code
button.buttonTintList=ColorStateList.valueOf(getColor(R.color.red))

Use Below Code:
button.setBackgroundTintList(ColorStateList.valueOf(resources.getColor(R.id.red)));

Related

How to create TextInputLayout with OutlineBox programmatically

I want to create TextInputLayout with Widget.MaterialComponents.TextInputLayout.OutlinedBox style. I tried many ways but couldn't get the required result.
Here is my code.
TextInputLayout textInputLayout = new TextInputLayout(getActivity(),null,R.style.Widget_MaterialComponents_TextInputLayout_OutlinedBox);
textInputLayout.setHint("My Hint");
TextInputEditText editText = new TextInputEditText(textInputLayout.getContext());
textInputLayout.addView(editText);
parentView.addView(textInputLayout);
I also tried:
TextInputLayout textInputLayout = new TextInputLayout(getActivity(),null,TextInputLayout.BOX_BACKGROUND_OUTLINE);
I want to create view like this .
UPDATE
Thanks to #Mike M.
You need to use TextInputLayout.setBoxBackgroundMode() method to use OutlineBox style
setBoxBackgroundMode (int boxBackgroundMode)
Set the mode for the box's background (filled, outline, or none).
Then you need to use TextInputLayout.BOX_BACKGROUND_OUTLINE) Constants
NOTE: To get the corner in your OutlineBox of TextInputLayout you need to use setBoxCornerRadii() method
SAMPLE CODE
public class MainActivity extends AppCompatActivity {
LinearLayout parentView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
parentView = findViewById(R.id.parentView);
TextInputLayout emailTextInputLayout = new TextInputLayout(this, null, R.style.Widget_MaterialComponents_TextInputLayout_OutlinedBox);
emailTextInputLayout.setHint("Please Enter Email Address");
emailTextInputLayout.setBoxBackgroundMode(TextInputLayout.BOX_BACKGROUND_OUTLINE);
emailTextInputLayout.setBoxCornerRadii(5, 5, 5, 5);
TextInputEditText edtEmail = new TextInputEditText(emailTextInputLayout.getContext());
emailTextInputLayout.addView(edtEmail);
parentView.addView(emailTextInputLayout);
TextInputLayout passTextInputLayout = new TextInputLayout(this, null, R.style.Widget_MaterialComponents_TextInputLayout_OutlinedBox);
passTextInputLayout.setHint("Please Enter Password");
passTextInputLayout.setBoxBackgroundMode(TextInputLayout.BOX_BACKGROUND_OUTLINE);
passTextInputLayout.setBoxCornerRadii(5, 5, 5, 5);
TextInputEditText edtPass = new TextInputEditText(passTextInputLayout.getContext());
passTextInputLayout.addView(edtPass);
parentView.addView(passTextInputLayout);
}
}
OUTPUT
Based on this answer: https://stackoverflow.com/questions/3246447/how-to-set-the-style-attribute-programmatically-in-android
Dynamic style change is not currently supported. You must set the style before the view is created (in XML).
That's the reason that TextInputLayout does not programmatically accept setting the outline boxed style.
Here is the simple solution:
You can use LayoutInflater
Instantiates a layout XML file into its corresponding View objects.
DEMO
Create a new layout
<?xml version="1.0" encoding="utf-8"?>
<android.support.design.widget.TextInputLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/userIDTextInputLayout"
style="#style/Widget.MaterialComponents.TextInputLayout.OutlinedBox"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_margin="10dp">
<android.support.design.widget.TextInputEditText
android:id="#+id/userIDTextInputEditText"
android:layout_width="match_parent"
android:hint="Enter User Name"
android:layout_height="wrap_content" />
</android.support.design.widget.TextInputLayout>
AndroidX (+Material Components for Android):
<?xml version="1.0" encoding="utf-8"?>
<com.google.android.material.textfield.TextInputLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/userIDTextInputLayout"
style="#style/Widget.MaterialComponents.TextInputLayout.OutlinedBox"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_margin="10dp">
<com.google.android.material.textfield.TextInputEditText
android:id="#+id/userIDTextInputEditText"
android:layout_width="match_parent"
android:hint="Enter User Name"
android:layout_height="wrap_content" />
</com.google.android.material.textfield.TextInputLayout>
Now using LayoutInflater add that TextInputLayout in your required layout
public class MainActivity extends AppCompatActivity {
LinearLayout rootView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
rootView = findViewById(R.id.rootView);
View view = LayoutInflater.from(this).inflate(R.layout.temp_layout, null);
TextInputLayout userNameIDTextInputLayout=view.findViewById(R.id.userIDTextInputLayout);
TextInputEditText userNameInputEditText = view.findViewById(R.id.userIDTextInputEditText);
userNameIDTextInputLayout.setHint("Please Enter User Name");
rootView.addView(view);
}
}
OUTPUT
Note
If you want to add a TextInputLayout from XML, then please check out the following answer:
Outlined Edit Text from Material Design
If you want to add more than 5 TextInputLayouts programmatically, then please consider using a RecyclerView. Check out the following answers:
Dynamic form with repeating form
How can I validate recyclerview adapter TextInputEditText from fragment?
Hope this helps!
You can use the method applyStyle defined on the Theme class. In Kotlin, you can access it with the theme property on a Context (or subclass) instance.
The applyStyle function allows you to add a style to the current theme, that defines theme attributes referencing styles. After calling this method, you can pass the attribute as the third parameter of a View, like TextInputLayout, which will apply the desired styles while respecting the theme.
I used this technique in Splitties (a library which I authored), and there's some documentation plus examples that should help you: https://github.com/LouisCAD/Splitties/blob/v3.0.0-alpha02/views-dsl/README.md#using-styles-defined-in-xml
I did not yet add first class support for themes from Material Components in Splitties Views DSL, but you can do it yourself, and you can even open an issue to discuss it, or contribute so it gets integrated sooner.
This is how i did it, notice that you have to pass the context of TextInputLayout to TextInputEditText so that the style is passed on correctly.
[ src: https://material.io/components/text-fields/android#filled-text-field ]
val lp = LinearLayout.LayoutParams(
LinearLayout.LayoutParams.MATCH_PARENT,
LinearLayout.LayoutParams.WRAP_CONTENT
)
val etInputLayout = TextInputLayout(context)
lp.setMargins(16, 16, 16, 16)
etInputLayout.layoutParams = lp
etInputLayout.boxBackgroundMode = TextInputLayout.BOX_BACKGROUND_OUTLINE
etInputLayout.boxBackgroundColor = Color.WHITE
etInputLayout.setBoxCornerRadii(8f, 8f, 8f, 8f)
val etInput = TextInputEditText(etInputLayout.context)
etInput.layoutParams = lp
etInputLayout.addView(etInput, lp)

Android how to change the button color by the text

I simply wish to change the background color of the button by the value of the text. For example, when I change the text to:
button.setText("YES");
I want to set the background color of the button to green.
and when I change the text to:
button.setText("NO");
I want to set the background color of the button to red.
When I change it in the java code like this:
boolean textValueYES = true;
button.setBackgroundColor(textValueYES ? Color.GREEN : Color.RED);
The button loses its drawable.xml settings.
Is there a way to add this checking to the drawable xml?
Or to set the background color by its text value without losing the drawable settings?
you can create two drawable xml for red and green background color and set that xml programmatically.
button.setBackgroundResource(textValueYES ? R.drawable.green : R.drawable.red);
You have to do like this just write below of setText()
i.e
button.setText("YES");
setBackgroundResource(R.color.green);
and when
button.setText("NO");
setBackgroundResource(R.color.red);
i do like this in my java file
final Button btn_showtouch = (Button)findViewById(R.id.button);
btn_showtouch.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if((btn_showtouch.getText()).equals("YES")) {
btn_showtouch.setBackgroundColor(Color.GREEN);
btn_showtouch.setText("NO");
}else if(btn_showtouch.getText().equals("NO")) {
btn_showtouch.setBackgroundColor(Color.CYAN);
btn_showtouch.setText("YES");
}
}
});
}
and your XML file like this
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="YES"
android:id="#+id/button"
android:layout_below="#+id/textView"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:layout_marginTop="62dp" />
and its worked for me i hope this will help you

Change the background color of the layout programmatically

Android Studio 0.4.6
minSdkVersion 10
targetSdkVersion 19
I have an activity called ReadingLamp and a Relativelayout called activity_reading_lamp.xml.
I am programmatically trying to set the layout to a different background color.
In my onCreate and set the content view to this layout.
setContentView(R.layout.activity_reading_lamp);
I try and get the root view by doing the following:
mActivityBackground = getWindow().getDecorView().getRootView();
Then later in my app I want to change the color so I do like this:
mActivityBackground.setBackgroundColor(Color.parseColor("#0cf5ff"));
However, the above line doesn't do anything to change the background.
I have also tried doing the following:
mActivityBackground = (RelativeLayout)findViewById(R.layout.activity_reading_lamp);
Where am I going wrong in my code?
you have declared, setContentView(R.layout.activity_reading_lamp); in your Activity. Then you should look for the view you want to change the background color. It has to belongs to R.layout.activity_reading_lamp.
View view = findViewById(R.id.declared_inside_reading_lamp);
Then you can call
view.setBackgroundColor(Color.GREEN)
You have to ensure that all layouts in your activity_reading_lamp.xml have transparent background
You need to specify which background you need to set. For example, you can make id for the parent layout on your activity then do:
RelativeLayout parentLayout = (RelativeLayout)findViewById(R.id."your parent layout id and not your activity name");
parentLayout.setBackgroundColor(Color.TRANSPARENT);
If you would like to make a transition to the new color try this:
#SuppressLint("NewApi") private void tintColor(View rootView, String newColor) {
// currentColor can be given as a new parameter or set as a field
ColorDrawable[] color = {
new ColorDrawable(Color.parseColor(currentColor)),
new ColorDrawable(Color.parseColor(newColor)) };
TransitionDrawable trans = new TransitionDrawable(color);
int sdk = android.os.Build.VERSION.SDK_INT;
if (sdk < android.os.Build.VERSION_CODES.JELLY_BEAN) {
rootView.setBackgroundDrawable(trans);
} else {
rootView.setBackground(trans);
}
trans.startTransition(ANIMATION_TIME); // ANIMATION_TIME : time in milliseconds
}
The code accepts hex color strings.
RelativeLayout rl = (RelativeLayout)findViewById(R.id.your_layout_id);
rl.setBackgroundColor(Color.RED);

How can I programmatically set android:button="#null"?

I'm trying to programmatically add a set of RadioButtons to a RadioGroup like so:
for (int i = 0; i < RANGE; i++) {
RadioButton button = new RadioButton(this);
button.setId(i);
button.setText(Integer.toString(i));
button.setChecked(i == currentHours); // Select button with same index as currently selected number of hours
button.setButtonDrawable(Color.TRANSPARENT);
button.setBackgroundResource(R.drawable.selector);
button.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View view) {
((RadioGroup)view.getParent()).check(view.getId());
currentHours = view.getId();
}
});
radioGroupChild.addView(button);
}
and I need to set the button drawable to null (I want just text on top of my background). Manually doing this in the XML with android:button="#null" works great, but I don't want to hardcode each radio button. I've tried just doing button.setButtonDrawable(null) but it doesn't change anything.
Any help is greatly appreciated!
You need to set an empty StateListDrawable as the drawable. So the Java equivalent of android:button="#null" is:
radioButton.setButtonDrawable(new StateListDrawable());
You should do this:
button.setBackgroundDrawable(null);
If your drawable has a reference to selector you can make it transparent through your selector xml:
<item android:drawable="#android:color/transparent" />
as you'd probably found the solution ;)
setButtonDrawable(getResources().getDrawable(android.R.color.transparent))
should do the trick.
Only this worked for me.
What worked for me in multiple devices and APIs and is as simple as it gets was setButtonDrawable(android.R.color.transparent);
in Kotlin you can do that
radioButton.buttonDrawable = null

ImageButton Property Check

I have an ImageButton which on click i show a dialog box where users can either take a photo from the camera or choose from the gallery. On selecting image from either sources i setBitmap for that ImageButton to the image selected like this
SelectedPhoto = BitmapFactory.decodeFile(selectedImagePath);
DisplayPhoto.setImageBitmap(SelectedPhoto);
Now when some one has already selected an image and click the image again i want to show a different dialog which contains a third option "Remove Photo".
What property of the image button should i check and against what ?
ImageButton in XML
<ImageButton
android:id="#+id/DisplayPhoto"
android:layout_width="95dip"
android:layout_height="95dip"
android:layout_marginRight="8dip"
android:background="#drawable/signup_photo_selector" android:scaleType="centerCrop" />
ImageButton Background XML
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:drawable="#drawable/signup_form_photo_selected" android:state_pressed="true"/>
<item android:drawable="#drawable/signup_form_photo"/>
</selector>
Would imgButton.getDrawable() work, since it returns null if no drawable has been assigned to the imagebutton?
If not, or if you don't want to get the entire drawable just to see if it's there, you can use a tag. imgButton.setTag(object) lets you store any object within the imagebutton... every time you set its background, you can tag a value that identifies whether its background was set. You could even use different values to differentiate whether you set its background using a camera or from the gallery, if that's useful. When you want to see if the imagebutton has a background or not, use imgButton.getTag() to retrieve the object.
Edit. Here is how you would use setTag and getTag. I will use an Integer object as the ImageButton's tag, where a value of 0 indicates no background has been set and a value of 1 indicates a background has been set. You can use an enum or final variables if you want to make the code a bit clearer, but using an Integer will work as an example.
public class MainActivity extends Activity, implements OnClickListener {
private ImageButton imgButton;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
imgButton = (ImageButton)findViewById(R.id.imgID);
imgButton.setTag(new Integer(0)); // no background
...
}
public void onClick(View view) {
ImageButton ib = (ImageButton)view;
int hasBackground = ib.getTag().intValue();
if(hasBackground==0) {
// imagebutton does not have a background. do not include remove option
...
} else {
// imagebutton has a background. include remove option
}
}
}

Categories

Resources