Android Kotlin - Changing the background of a button programmatically - android

How can I change the background of a button programmatically with Android using Kotlin?

This is the way to change background programmatically :
button.backgroundTintList = ContextCompat.getColorStateList(this, R.color.yourColor)

<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"
android:shape="rectangle">
/// write your custome code here...
</shape>
create drawable in /app/src/main/res/drawable/btn_drawable.xml
and set it as background of button.
button.setBackgroundResource(R.drawable.btn_drawable);
Change background on button click :
button.setOnClickListener {
if(isThemeOne){
button.setBackgroundResource(R.drawable.btn_drawable_1);
isThemeOne=false;
} else {
button.setBackgroundResource(R.drawable.btn_drawable_2);
isThemeOne=true;
}
}

try this easy way for all version
if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.M) {
btn.setBackgroundColor(getColor(R.color.black))
}else{
btn.setBackgroundColor(resources.getColor(R.color.black))
}

Related

restore default animation view of .setOnClickListener

The Image of the issue
Before clicked, the view of "setOnClickListener" is like the right picture
The action of code setOnClickListener:
card_sales.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
view.startAnimation(fade);
if(m_inventory.equals("1")){
card_sales.setBackgroundColor(getResources().getColor(R.color.white_greyish));
Intent profil = new Intent(getActivity(),InventoryActivity2.class);
startActivity(profil);
}else if(m_inventory.equals("0") || m_inventory.equals("") || m_inventory == null){
Toast.makeText(getActivity(),"Access Denied",Toast.LENGTH_LONG).show();
}
}
});
then i press back button from the activity
#Override
public void onBackPressed() {
finish();
formstock.setVisibility(View.VISIBLE);
}
and then the "setOnClickListener" view is like on the left picture.
Please, give me solution for this issue :(
You shouldn't set a fixed color when button clicked with setBackgroundColor. instead use selector for background
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:state_pressed="true">
<color android:color="#color/white_greyish" />
</item>
<item>
<color android:color="#color/white" />
</item>
</selector>
Save this file in drawable folder and set this in XML for card_sales
android:background="#drawable/filename"
imho even better effect (ripple) you can achieve with default selector
android:background="?android:attr/selectableItemBackground"
btw. when you call finish() then this Activity gets destroyed, so its unnecessary to call formstock.setVisibility(View.VISIBLE);. if you really need to show something at that moment and with above line it works as you expected - you have very wrong architecture and some memory leak for sure

my list (Recyclerview) displays on multiple screens want to change the background colour of list item on only one screen

This is my viewholderClass which displays the list on multiple screen.
class TagViewHolder(itemView: View, listener: RecyclerViewItemClickListener?,isTraining: Boolean) : BaseViewHolder<AdapterTag>(itemView, listener) {
override fun onBindView(context: Context, data: AdapterTag ) {
itemView.tag_icon.setImageResource(data.getIconResId())
itemView.tag_name.text = data.getTitle()
itemView.tag_count.text = "[${data.getItemCount()}]"
//background color change of selected item in list
itemView.isSelected = (data.getItemCount() == 0)
}
}
this is my drawable class which implements in below drawable class for background colour change.
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item>
<shape android:shape="rectangle">
<corners android:radius="#dimen/card_radius" />
<padding android:bottom="#dimen/card_vertical_padding"
android:left="#dimen/card_horizontal_padding"
android:right="#dimen/card_horizontal_padding"
android:top="#dimen/card_vertical_padding" />
<solid android:color="#color/cardBackgroundWithZeroItem"/>
</shape>
</item>
</selector>
this is my list background class which changes the background colour in selected_state.
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:state_selected="true" android:drawable="#drawable/training_tag_card_state"/>
<item>
<shape android:shape="rectangle">
<corners android:radius="#dimen/card_radius" />
<padding android:bottom="#dimen/card_vertical_padding"
android:left="#dimen/card_horizontal_padding"
android:right="#dimen/card_horizontal_padding"
android:top="#dimen/card_vertical_padding" />
<solid android:color="#color/cardBackground"/>
</shape>
</item>
</selector>
My recycler view list displays on multiple screen but i have to change the background color of list items only on particular screen but in the tagViewHolder it changes background color of list items on everyscreen how to use the isTraining:Boolean(it is for my screen i want to change background color of list items) such that i can use background color on desired screen of list items.what should i change in implemetations to get the solution of above problem.
Pass any value to the adapter from the activity. Based on that Boolean value you have changed the background.
You need to pass isTraining Boolean value through adapter
For ex : You have 2 Activities
A and B , You want change the List Item Background in A Activity only for that u need to pass the isTraining value True
if (isTraining) {
itemView.parentView.background =
ContextCompact.getDrawable(itemView.parentView.context, R.drawable.resourceid)
} else {
//Default value
ContextCompact.getDrawable(itemView.parentView.context, R.drawable.resourceid)
}
class TagViewHolder(itemView: View, listener: RecyclerViewItemClickListener?,private val isTraining:Boolean) : BaseViewHolder<AdapterTag>(itemView, listener) {
override fun onBindView(context: Context, data: AdapterTag) {
itemView.tag_icon.setImageResource(data.getIconResId())
itemView.tag_name.text = data.getTitle()
itemView.tag_count.text = "[${data.getItemCount()}]"
itemView.isSelected = (data.getItemCount() == 0) && isTraining
}
}
declaring a private variable and providing it in a condition "isTraining".
using this variable in parent class to define the condition true for the particular screen adapter.

I want to Change the backgroud Colo of Specific Recycler VIew Item

I want to change the Background Color Green OF the Recycler View data Whose Status IS Ture and Set Backround Color RED whose status is False.
The Round One Status is True and rest are False.
So can any one tell me how i Differentiate ...
My Recycler View code Write Below.
#Override
public void onBindViewHolder(DocRecycleAdoptor.MyViewHolder holder, int position) {
final EmpAttandance empAttandance = mDocs.get(position);
holder.txtDocID.setText(empAttandance.getDOC_ID());
holder.txtEmpID.setText(empAttandance.getEMP_ID());
holder.dateTime.setText(empAttandance.getDATE()+" "+empAttandance.getTIME());
holder.txtCoID.setText(empAttandance.getCO_ID());
holder.txtStatus.setText(empAttandance.getSA());
holder.empName.setText(empAttandance.getEmpName());
if(empAttandance.getStatus() == "True"){
holder.itemView.setBackgroundColor(Color.GREEN);
}else{
holder.itemView.setBackgroundColor(Color.RED);
}
}
Now it Shows like This.
But I want When Status is False Color Will Red.
it didit hapen.
top three Status are True And Other is false.
Showing all in same color
In your onBindViewHolder add below check
if(empAttandance.getStatus()){
//set your desired color on textview or a view for status true
}else{
//set your desired color on textview or a view for status false
}
#Override public void onBindViewHolder(DocRecycleAdoptor.MyViewHolder holder, int position) {
final EmpAttandance empAttandance = mDocs.get(position);
holder.txtDocID.setText(empAttandance.getDOC_ID());
holder.txtEmpID.setText(empAttandance.getEMP_ID());
holder.dateTime.setText(empAttandance.getDATE()+" "+empAttandance.getTIME());
holder.txtCoID.setText(empAttandance.getCO_ID());
holder.txtStatus.setText(empAttandance.getSA());
holder.empName.setText(empAttandance.getEmpName());
// this is it
holder.rootLayout.setBackgroundColor(empAttandance.getStatus() ? GREEN : RED);
}
inside your activity_docattd_list_items add linear layout.
add inside linearlayout a drawable #drawarble/selector_gray_view.
#selector_gray_view.xml
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:drawable="#drawable/gradient_gray_light"
android:state_pressed="true"/>
<item android:drawable="#color/clicked"
android:state_focused="true"/>
</selector>
and after that add drawble #gradient_gray_light.
#gradient_gray_light.xml
<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"
android:shape="rectangle">
<gradient android:startColor="#30888888"
android:endColor="#30888888"
android:angle="90" />
</shape>`enter code here`
and after that add another drawable ,
click inside your selector_gray_view.xml,
#drawable/color.
and also intialize linearlayout in myviewholder.
use it inside onbindviewholder like as:
holder.linearlayout.setonclicklistener(new View.OnClickListener() {
#Override
public void onClick(View v) {
}
);
happy coding.
In ANdroid == are Not working. so i use empAttandance.getStatus().equal("True") instead Of == and its working Fine.
Thanks to All of you Guys for helping me out. much appreciate.
if(empAttandance.getStatus().equal("True")){
//set your desired color on textview or a view for status true
}else{
//set your desired color on textview or a view for status false
}

How to create circular widget in android whose color can programmatically be changed?

Is there any way to create a circular button in android without just setting drawable shape file as background? Because I want to set button color programmatically and by setting drawable shape file as background it doesn't work. I also used Floating action Button but when tried to set color swatch as background it didnt work.
`public class MainActivity extends AppCompatActivity implements View.OnClickListener {
FloatingActionButton fab1, fab2, fab3, fab4, fab5,fab6;
ImageView imgV;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
fab1 = (FloatingActionButton) findViewById(R.id.bt1);
fab2 = (FloatingActionButton) findViewById(R.id.bt2);
fab3 = (FloatingActionButton) findViewById(R.id.bt3);
fab4 = (FloatingActionButton) findViewById(R.id.bt4);
fab5 = (FloatingActionButton) findViewById(R.id.bt5);
fab6 = (FloatingActionButton) findViewById(R.id.bt6);
imgV = (ImageView) findViewById(R.id.imageView);
fab1.setOnClickListener(this);
fab2.setOnClickListener(this);
fab3.setOnClickListener(this);
fab4.setOnClickListener(this);
fab5.setOnClickListener(this);
Bitmap bitmap = ((BitmapDrawable) imgV.getDrawable()).getBitmap();
if (bitmap != null) {
Palette.from(bitmap).maximumColorCount(10).generate(new Palette.PaletteAsyncListener() {
#Override
public void onGenerated(Palette palette) {
setViewSwatch(fab1, palette.getVibrantSwatch(), "Vibrant");
setViewSwatch(fab2, palette.getDarkVibrantSwatch(), "Dark Vibrant");
setViewSwatch(fab3, palette.getLightVibrantSwatch(), "Light Vibrant");
setViewSwatch(fab4, palette.getMutedSwatch(), "Muted");
setViewSwatch(fab5, palette.getLightMutedSwatch(), "Light Muted");
}
});
}
}
private void setViewSwatch(FloatingActionButton fab, Palette.Swatch vibrantSwatch, String vibrant) {
if (vibrantSwatch != null) {
fab.setBackgroundColor(vibrantSwatch.getRgb());
}
}
`
I highly recommend you using Floating Action Button which is circle you can easily change its color programmatically
mFab.setBackgroundTintList(ColorStateList.valueOf(your color in int))
Also here is link for more info
I think you may waste your time by implementing other solutions (ways) that goes the exact same result
Hope this helps ;)
Our friend 'markushi' wrote this code for Android circular button, maybe it can help you
https://github.com/markushi/android-circlebutton
If you require your circular button to alternate between two colours only this is the easiest solution:
Create two new Drawable XML files as d1 and d2
d1.xml
<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"
android:shape="rectangle" >
<solid android:color="#000000(Required colours hex value here)" />
<corners android:radius="10dip" />
<stroke
android:width="1dp"
android:color="#android:color/white" />
</shape>
Create a copy of d1.xml as d2.xml and just modify the colour value
In code you can programatically change the background as follows:
v.setBackgroundResource(R.drawable.d1);
v.setBackgroundResource(R.drawable.d2);

Design BottomNavigationView - set background color in code

Is there any way to set the background color of the new design libraries BottomNavigationView in code to a custom color value instead of a color resource? Any "trick" maybe?
My current solution:
I make the BottomNavigationView transparent
I add a second view behind the bottomNavigationView
I update this view's background
But this looks ugly, especially as I have to use a custom behaviour for the background view to be animated in parallel with the BottomNavigationView in the parent CoordinatorLayout...
Solved it myself.
Solution 1
I just setup all items with a transparent background (this needs one resource file only) and then I theme the BottomNavigationView actual background itself.
bottomBar.setBackground(new ColorDrawable(color));
bottomBar.setItemBackgroundResource(R.drawable.transparent);
Resource drawable - transparent.xml
<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android" android:shape="rectangle">
<solid android:color="#android:color/transparent" />
</shape>
Solution 2 - via reflection (support library 25.0.0)
public void themeBottomBarBackgroundWithReflection(BottomNavigationView bottomBar, int color)
{
try
{
Field mMenuViewField = BottomNavigationView.class.getDeclaredField("mMenuView");
mMenuViewField.setAccessible(true);
BottomNavigationMenuView mMenuView = (BottomNavigationMenuView)mMenuViewField.get(bottomBar);
Field mButtonsField = BottomNavigationMenuView.class.getDeclaredField("mButtons");
mButtonsField.setAccessible(true);
BottomNavigationItemView[] mButtons = (BottomNavigationItemView[])mButtonsField.get(mMenuView);
for (BottomNavigationItemView item : mButtons) {
ViewCompat.setBackground(item, new ColorDrawable(color));
}
}
catch (NoSuchFieldException e)
{
e.printStackTrace();
}
catch (IllegalAccessException e)
{
e.printStackTrace();
}
}
After many search, only this resolve my case:
bottomNavigationView.setItemBackground(new ColorDrawable(color));
Here I set each one of background item.

Categories

Resources