Button.setBackground(Drawable background) throws NoSuchMethodError - java

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.

Related

Increase height of selected icon in navigation bottom view android when using custom icon?

Please, I want to use custom icon for bottom navigation view in android like this. How to change icon position when selected? When they are selected they go up a bit. Do you create a selected icon with a certain margin or is there a way to set the height in android? This image is from a flutter library though. I want to reproduce that in an Android Java project. Or find a library that implement it
Inside your bottomNavigationView.setOnNavigationItemSelectedListener for each icon pressed call that animation method animateBottomIcon(int itemIndex, boolean isChecked).
BottomNavigationView bottomNav;
BottomNavigationMenuView menuView;
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
bottomNav.setClipChildren(false);
bottomNav.setClipToPadding(false);
bottomNav.setClipToOutline(false);
menuView.setClipChildren(false);
menuView = (BottomNavigationMenuView) bottomNav.getChildAt(0);
}
private void animateBottomIcon(int itemIndex, boolean isChecked) {
final View view = menuView.getChildAt(itemIndex).findViewById(com.google.android.material.R.id.icon);
ObjectAnimator translateUpAnimator = ObjectAnimator.ofFloat(view, "translationY",
0,
(float) (-(bottomNav.getHeight() / 2))).setDuration(500);
if(!isChecked) {
translateUpAnimator.start();
}
if(currentItemIndex != -1) {
final View currentView = menuView.getChildAt(currentItemIndex).findViewById(com.google.android.material.R.id.icon);
ObjectAnimator translateDownAnimator = ObjectAnimator.ofFloat(currentView, "translationY",
0,
(float) (-(bottomNav.getHeight() / 2))).setDuration(500);
if (!isChecked) {
translateDownAnimator.reverse();
}
}
}
Usually the menu icon will be cut off by the BottomNavigation to avoid that use: android:clipChildren="false" on the root view of your layout, and in your java class, inside onCreateView():
bottomNav.setClipChildren(false);
bottomNav.setClipToPadding(false);
bottomNav.setClipToOutline(false);
and most importantly on your menuItem, because it's the parent of your icon items. menuView.setClipChildren(false);.
Remember to give your bottom navigation view a fixed height.
<com.google.android.material.bottomnavigation.BottomNavigationView
android:id="#+id/bottom_nav"
android:layout_width="match_parent"
android:layout_height="56dp"
app:layout_constraintBottom_toBottomOf="parent"
android:layout_gravity="bottom"
android:background="#color/white"
app:itemIconSize="54dp"
app:elevation="12dp"
app:labelVisibilityMode="unlabeled"
app:menu="#menu/menu_bottom_nav">[![enter image description here][1]][1]
UPDATE: The library is live here https://github.com/Kwasow/BottomNavigationCircles-Android
I stumbled upon your question and created a custom android navigation bar inspired by the design.
The navigation bar looks like this:
The code for it is located here: https://github.com/Kwasow/Archipelago/blob/main/app/src/main/java/com/github/kwasow/archipelago/views/CustomBottomNavigation.kt
The bg_green_circle.xml drawable looks like this:
<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"
android:shape="oval">
<size
android:width="24dp"
android:height="24dp"/>
<solid android:color="#6CB86A"/>
</shape>
I might turn it into a package in the future, but it still requires some work. I'll update the post if it happens.
You can do this by using a selector.
For this you need two separate images:
1) when state selected is true means your selected image
2) default means when no icon is selected.
XML
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:state_selected="true"
android:drawable="#drawable/YOUR SELECTED IMAGE">
</item>
<item android:drawable="#drawable/YOUR DEFAULT IMAGE"></item>
</selector>
Then use this selector as a drawable for each image icon for the bottom navigation view.
You can add other attributes in selector a/c to your requirements.

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!!))
}

Change BackgroundTint of ImageView on Android

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"/>

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

Categories

Resources