Change BackgroundTint of ImageView on Android - java

I have an ImageButton which have a drawable background resource which is oval shape.
<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"
android:shape="oval">
<solid
android:angle="270"
android:color="#FFFF0000" />
</shape>
Here is the ImageButton in XML:
<ImageButton
android:id="#+id/c1"
android:layout_width="70dp"
android:layout_height="70dp"
android:layout_columnSpan="1"
android:layout_rowSpan="1"
android:background="#drawable/circle"
android:layout_margin="10dp"
/>
I need to change the color of the circle shape dynamically, this will be done by either change the backgroundTint property in the ImageButton or change the circle shape color.
NOTE:
I have array of strings that stores a list of RGB colors i need to use these RGB colors.

You can do it like this:
mImageView.setBackgroundTintList(getResources().getColorStateList(R.color.my_color));
Or you can do better, to support versions pre LOLLIPOP:
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP)
{
ColorStateList stateList = ColorStateList.valueOf(getResources().getColor(R.color.my_color));
mImageView.setBackgroundTintList(stateList);
}
else
{
mImageView.getBackground().getCurrent().setColorFilter(
new PorterDuffColorFilter(getResources().getColor(R.color.my_color),
PorterDuff.Mode.MULTIPLY));
}
More about PorterDuffColorFilter here.

i just found the answer, it works as follow:
In my changeColors(int id) function
Create ImageButton variable.
Assign the passed id to the ImageButton variable.
Define GradientDrawable variable to store the ImageButton background.
Update the color of the background using GradientDrawable variable.
Update the ImageButton to the new background.
This is the code:
ImageButton circle;
circle = (ImageButton) findViewById(id);
GradientDrawable drawable = (GradientDrawable) getResources().getDrawable(R.drawable.circle);
drawable.setColor(Color.parseColor("color in format #FFFFFF");
circle.setBackground(drawable);

You may use ImageView instead and use app:tint to set the tint color for the background drawable.
<ImageView
android:layout_width="20dp"
android:layout_height="20dp"
android:src="#drawable/circle"
app:tint="#android:color/holo_red_dark"/>

Related

How to change stroke color of a drawable with Kotlin or Java

I have a drawable object that I use to set the background of a linear layout, leaving the linear with the circular shape with a semi transparent orange line. but at some point in the code I need to change the color of this background (drawable object) to a color that I have only as a parameter and I don't have it in the colors of my color file. I need to change the stroke color of this drawable to a color that I have in one of my runtime variables
bg_static_show_password.xml
<shape xmlns:android="http://schemas.android.com/apk/res/android"
android:shape="oval">
<!-- center circle -->
<stroke android:color="#color/accent_color_alpha"
android:width="3dp" />
<solid android:color="#android:color/transparent" />
<size
android:width="28dp"
android:height="28dp"/>
</shape>
linear layout
<android.support.constraint.ConstraintLayout
android:id="#+id/card_show_password"
android:layout_width="#dimen/anim_layout_size"
android:layout_height="#dimen/anim_layout_size"
android:layout_marginTop="#dimen/anim_margin_top"
android:background="#drawable/bg_static_show_password"
android:layout_gravity="center"
app:layout_constraintTop_toBottomOf="#id/view_group_item"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent">
method I'm trying to use to make this color change
fun showAlternativeForAnimation(view: LinearLayout) {
val drawable = view.background as GradientDrawable
val theme = PasswordRecoveryTheme(ApplicationSession.instance?.themeId)
drawable.setStroke(1, theme.getAccentColor(ApplicationFactory.context!!))
}
the parameter of method is the LinearLayout
When I try, I get this exception:
kotlin.TypeCastException: null cannot be cast to non-null type android.graphics.drawable.GradientDrawable
Make a safe cast (as?), ensure that the view you pass has a shape drawable set as it's background and change parameter to view: View so as to allow usage for any view(LinearLayout, ConstraintLayout, etc).
fun showAlternativeForAnimation(view: View) {
val drawable = view.background as? GradientDrawable
val theme = PasswordRecoveryTheme(ApplicationSession.instance?.themeId)
drawable?.setStroke(1, theme.getAccentColor(ApplicationFactory.context!!))
}

Android : Removing border in rating bar

I am using default rating bar in android and there is a weird grey border is been showing, I want to remove them.
Please Note :: Many answers on stackoverflow suggest to use own images but I don't want to, Is there is any method to remove border?
My code ::
<RatingBar
android:id="#+id/layout_fragment_home_recycler_view_rating_bar1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:numStars="5"
android:stepSize="1.0"
android:rating="4.0"
style="?android:attr/ratingBarStyleSmall"
android:layout_marginTop="10dp"
android:layout_marginBottom="7dp"
android:layout_marginLeft="7dp" />
What I am getting
Just remove
style="?android:attr/ratingBarStyleSmall"
From your layout
Create custom style to your rating bar
<style name="RatingBarStyle" parent="#android:style/Widget.RatingBar">
<item name="android:progressDrawable">#drawable/ratingbar_selector</item>
<item name="android:minHeight">34dp</item>
<item name="android:maxHeight">34dp</item>
</style>
your rating bar selector
drawable/ratingbar_selector.xml
<item android:id="#+android:id/background"
android:drawable="#drawable/..." />
<item android:id="#+android:id/secondaryProgress"
android:drawable="#drawable/..." />
<item android:id="#+android:id/progress"
android:drawable="#drawable/..." />
This worked for me:
RatingBar coachRating = (RatingBar) findViewById(R.id.rcoach_rbr_rating);
LayerDrawable stars = (LayerDrawable) coachRating.getProgressDrawable();
stars.getDrawable(2).setColorFilter(ContextCompat.getColor(itemView.getContext(),
R.color.colorAccent),PorterDuff.Mode.SRC_ATOP); // for filled stars
stars.getDrawable(1).setColorFilter(ContextCompat.getColor(itemView.getContext(),
R.color.white), PorterDuff.Mode.SRC_ATOP); // for half filled stars
stars.getDrawable(0).setColorFilter(ContextCompat.getColor(itemView.getContext(),
R.color.white), PorterDuff.Mode.SRC_ATOP); // for empty stars
Reference: How can I set the color of android rating bar's stroke? (Not the color of the stars but the BORDER)
Try this, it don't need images.
public static void setRatingStyle(RatingBar ratingbar, int ratingNormalColor, int ratingProgressColor) {
LayerDrawable stars = (LayerDrawable) ratingbar.getProgressDrawable();
stars.getDrawable(0).setColorFilter(ratingNormalColor, PorterDuff.Mode.SRC_ATOP);
stars.getDrawable(2).setColorFilter(ratingProgressColor, PorterDuff.Mode.SRC_ATOP);
}

How to add a one-side border and background into one drawable?

I have an ImageButton and to that in the android:background property I currently have a xml drawable which changes the ImageButton background color when pressed. This is all good but I also want to add a top border to each of these ImageButton's.
Here's a sample image I created to better get my point across.
These buttons will also have an active state which indicates the current active button and I can set that as a drawable using Java code.
You can use multiple drawables to get your work done. You can have drawable icons/images with the top border and the same without the top border and use the setBackgroundResource method to switch image backgrounds. (I believe you want to show the images with top border as currently selected tool icon, right?).
As you're going to construct several such image buttons like a toolbox, you'll have to make sure their selection states are controlled properly. If one image-button is selected all others should show the unselected drawable.
I threw together some codes and built this small example. Hope you'll find it useful.
public class MainActivity extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final ImageButton imButton1 = (ImageButton) findViewById(R.id.imButton1);
final ImageButton imButton2 = (ImageButton) findViewById(R.id.imButton2);
final ImageButton imButton3 = (ImageButton) findViewById(R.id.imButton3);
imButton1.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v)
{
imButton1.setBackgroundResource(R.drawable.icon1_selected);
imButton2.setBackgroundResource(R.drawable.icon2_unselected);
imButton3.setBackgroundResource(R.drawable.icon3_unselected);
}
});
imButton2.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v)
{
imButton1.setBackgroundResource(R.drawable.icon1_unselected);
imButton2.setBackgroundResource(R.drawable.icon2_selected);
imButton3.setBackgroundResource(R.drawable.icon3_unselected);
}
});
imButton3.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v)
{
imButton1.setBackgroundResource(R.drawable.icon1_unselected);
imButton2.setBackgroundResource(R.drawable.icon2_unselected);
imButton3.setBackgroundResource(R.drawable.icon3_selected);
}
});
}
}
And this is it's Layout:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#bbb"
tools:context="${packageName}.${activityClass}" >
<ImageButton
android:id="#+id/imButton1"
android:layout_toLeftOf="#+id/imButton2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginRight="0dp"
android:layout_alignTop="#+id/imButton2"
android:background="#drawable/icon1_unselected" />
<ImageButton
android:id="#id/imButton2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:layout_marginTop="23dp"
android:layout_alignParentTop="true"
android:background="#drawable/icon2_selected" />
<ImageButton
android:id="#+id/imButton3"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignTop="#id/imButton2"
android:layout_toRightOf="#id/imButton2"
android:background="#drawable/icon3_unselected" />
</RelativeLayout>
A screen-shot of the image buttons working.
Hope this helps.
I solved it by creating two seperate drawable xml files such that one has a top border and white color background and other one has same color border with a bit grey background. Then in the selector xml file all I had to do was assign each of these xml files to their respective states and problem solved. :)
try this
<?xml version="1.0" encoding="utf-8"?>
<layer-list xmlns:android="http://schemas.android.com/apk/res/android" >
<item
android:left="-6dp"
android:right="-6dp"
android:bottom="-6dp">
<shape>
<stroke
android:width="5dp"
android:color="#6c6c6c" />
<solid android:color="#FFFFFF" />
</shape>
</item>
</layer-list>
hey you may use view for border like that,you put this in your all side of your image view then you can see,
<View
android:layout_width="match_parent"
android:layout_height="1dp"
android:background="#000" />
whatever color you want to use. thanks

Button.setBackground(Drawable background) throws NoSuchMethodError

I'm implementing a simple method to add a Button to a LinearLayout programatically.
When I invoke the setBackground(Drawable background) method, the following Error is thrown:
java.lang.NoSuchMethodError: android.widget.Button.setBackground
My addNewButton method:
private void addNewButton(Integer id, String name) {
Button b = new Button(this);
b.setId(id);
b.setText(name);
b.setTextColor(color.white);
b.setBackground(this.getResources().getDrawable(R.drawable.orange_dot));
//llPageIndicator is the Linear Layout.
llPageIndicator.addView(b);
}
You might be testing on an API below level 16 (Jelly Bean).
The setBackground method is only available from that API level onwards.
I would try with setBackgroundDrawable (deprecated) or setBackgroundResource if that's the case.
For instance:
Drawable d = getResources().getDrawable(R.drawable.ic_launcher);
Button one = new Button(this);
// mediocre
one.setBackgroundDrawable(d);
Button two = new Button(this);
// better
two.setBackgroundResource(R.drawable.ic_launcher);
To create a homogeneous background for a View, you can create a drawable resource of type shape, and use that with the setBackgroundResource.
red_background.xml
<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android" android:shape="rectangle">
<solid android:color="#FF0000"/>
</shape>
Activity:
Button b = (Button)findViewById(R.id.myButton);
b.setBackgroundResource(R.drawable.red_background);
But this will look pretty bad, flat and out of place. If you want a colored button that looks like a button, than you can either design it yourself (rounded corners, stroke, gradient fill...) or a fast and dirty solution is to add a PorterDuff filter to the button's background:
Button b = (Button)findViewById(R.id.myButton);
PorterDuffColorFilter redFilter = new PorterDuffColorFilter(Color.RED, PorterDuff.Mode.MULTIPLY);
b.getBackground().setColorFilter(redFilter);
Since after Android 16 , the setBackgroundDrawable is deprecated, I suggested to checked before set code
you need to check current version of Android also
Button bProfile; // your Button
Bitmap bitmap; // your bitmap
if(android.os.Build.VERSION.SDK_INT < 16) {
bProfile.setBackgroundDrawable(new BitmapDrawable(getResources(), bitmap));
}
else {
bProfile.setBackground(new BitmapDrawable(getResources(),bitmap));
}
<Button
android:id="#+id/btnregister"
android:layout_width="150dp"
android:layout_height="45dp"
android:layout_gravity="center"
android:layout_marginHorizontal="10dp"
android:layout_marginVertical="20dp"
android:paddingVertical="5dp"
style="#style/btn_register"
android:text="Register"
android:textColor="#FFFFFF" />
apply below code in Styles.xml file :
<style name="btn_register">
<item name="android:layout_marginTop">15dp</item>
<item name="android:backgroundTint">#009688</item>
<item name="cornerRadius">20dp</item>
</style>
Change the theme from Theme.MaterialComponents to Theme.AppCompat
You can't use setBackground().
This method may be not available in your Android level.

Android Button with Drawable - Padding

I want to add a Drawable Image to my Button on the left and tried the following:
button = new Button(this);
button.setWidth(screen_dimens(0.25, "w")); //25% of screen width
button.setPadding(5, 5, 0, 5);
Drawable img = getResources().getDrawable(R.drawable.image);
button.setCompoundDrawablesWithIntrinsicBounds(img, null, null, null);
But I want to have a padding on the left between the drawable and the border of the button. Unfortunately, there is none.
Any help?
This will generate text + image button ( Image on Left & Text After That )
<Button
android:gravity="center_vertical"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/button2"
android:paddingLeft="20dp"
style="#style/whiteText"
android:onClick="openWhyAshoka"
android:drawableLeft="#drawable/arrow"
android:drawablePadding="50dp"
android:text="Ankit" />
You have to add the padding to you drawable, by changing the 9 slices content area or by changing your drawable padding:
<padding
android:bottom="10dp"
android:left="10dp"
android:right="10dp"
android:top="10dp" />
If you are using selector you have to add the padding rule to each one of the drawable states.
Use this API call:
public void setCompoundDrawablePadding (int pad)
Use this Code:
Drawable image = (Drawable)getResources().getDrawable(R.drawable.onstar_mute_unmute_button_selector);
ImageButton button=(ImageButton)findViewById(R.id.imageButton);
button.setPadding(0,10,5,0);
button.setGravity(Gravity.RIGHT);
button.setBackground(image);
<Button
android:id="#+id/otherapps"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#drawable/btn_background"
android:text="#string/other_apps"
android:layout_weight="1"
android:fontFamily="cursive"
android:layout_marginBottom="10dp"
android:drawableLeft="#drawable/ic_more"
android:paddingLeft="8dp" //for drawable padding to the left
android:textColor="#android:color/holo_red_light" />

Categories

Resources