Android change background of an XML file via java code - java

I have a Textview with an XML file attached to the background. Now I wanted to change the background of the Textview with setBackgroundColor(), but it doesn't work, because the background color of the XML file has to be changed. How do I change the background color of the my_border XML file?
XML Textview:
<TextView
android:id="#+id/textView7"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="150dp"
android:background="#drawable/my_border"
android:text="Hey"
android:textSize="24sp"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
XML Textview Border file:
<?xml version="1.0" encoding="utf-8"?>
<!-- View background color -->
<solid
android:color="#fff" >
</solid>
<!-- View border color and width -->
<stroke
android:width="1dp"
android:color="#000" >
</stroke>
<!-- The radius makes the corners rounded -->
<corners
android:radius="5dp" >
</corners>
<padding
android:left="10dp"
android:top="10dp"
android:right="10dp"
android:bottom="10dp">
</padding>

try this method
private void recolor(Context context, TextView textView, #ColorInt int color,int drawableResourceId) {
Drawable unwrappedDrawable = AppCompatResources.getDrawable(context, drawableResourceId);
if (unwrappedDrawable != null) {
DrawableCompat.wrap(unwrappedDrawable);
DrawableCompat.setTint(unwrappedDrawable, color);
textView.setBackground(unwrappedDrawable);
}
}
lets say you want a red background for your TextView then this will be as following
TextView mTextView = findViewById(R.id.textView7);
recolor(this, mTextView , getResources().getColor(R.color.red),R.drawable.my_border);

Related

BottomSheetDialog not rounding top corners correctly in Android

I have a custom BottomSheetDialog and for its layout i created drawable which has top corners rounded rectangle. BottomSheetDialog layout background is a Linearlayout and i applied drawable to the layout.Top corners of the bottom sheet rounding correctly but there is a another layout bottom of the Linear Layout which is not rounded (square and white see below picture) and it is not in the layout.xml file. its like rounded rectangle on top of a square.I couldn't get rid of that square.
Below is my custom bottom sheet sample
public abstract class EmployeeBottomSheetDialog extends BottomSheetDialog {
private Context context;
private Activity activity;
private RecyclerView employeeRecyclerView;
private EditText searchEditText;
private DataBase dataBase;
private ArrayList<Employe> employeeList = new ArrayList<>();
private ArrayList<Employe> employeeSelectedList = new ArrayList<>();
private SelectEmployeeAdapter selectEmployeeAdapter;
private ImageButton closeSearchImageButton;
public EmployeeBottomSheetDialog(#NonNull Context context, List<Employe> selectedEmployeeList) {
super(context,R.style.BottomSheetDialogStyle);
this.context = context;
this.activity = (Activity) context;
if(!selectedEmployeeList.isEmpty()){
employeeSelectedList.clear();
employeeSelectedList.addAll(selectedEmployeeList);
}
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.employee_bottom_sheet_dialog);
}
}
Below is my style
<style name="BottomSheetDialogStyle" parent="Theme.Design.Light.BottomSheetDialog">
<item name="android:windowIsFloating">false</item>
<item name="android:statusBarColor">#android:color/transparent</item>
<item name="android:windowSoftInputMode">adjustResize</item>
<item name="shapeAppearanceOverlay">#style/ShapeAppearanceOverlay</item>
<item name="backgroundTint">#android:color/transparent</item>
<item name="background">#android:color/transparent</item>
</style>
below is my bottom sheet layout.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:id="#+id/background"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical"
android:background="#color/transparent"
app:layout_behavior="#string/bottom_sheet_behavior">
<LinearLayout
android:id="#+id/dialog_layout"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical"
android:background="#drawable/bottom_sheet_background"
android:padding="10dp">
<ImageView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:src="#drawable/ic_baseline_arrow_drop_down_24" />
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="#dimen/between_two_views">
<com.google.android.material.textfield.TextInputLayout
android:id="#+id/search_wrapper"
style="#style/textInputHint"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="#string/search_employees">
<EditText
android:id="#+id/search"
style="#style/textInputText"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
</com.google.android.material.textfield.TextInputLayout>
<ImageButton
android:id="#+id/close_search"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentRight="true"
android:layout_marginTop="15dp"
android:background="#null"
android:src="#drawable/ic_baseline_close_24"
android:text="Button" />
</RelativeLayout>
<androidx.recyclerview.widget.RecyclerView
android:id="#+id/employee_recycler"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="#dimen/between_two_views"/>
</LinearLayout>
</LinearLayout>
Below is my rounded corner drawable
<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android">
<corners android:topLeftRadius="20dp" android:topRightRadius="20dp"/>
<solid android:color="#color/red" />
</shape>
To solve this, you need a transparent background color in your dialog style (BottomSheetDialogStyle):
<item name="android:colorBackground">#android:color/transparent</item>
For those looking for an easier way to implement rounded corners in all states, even EXPANDED state, then just define your BottomSheetDialog's background attribute to a shape drawable.
Here is the shape drawable:
<shape xmlns:android="http://schemas.android.com/apk/res/android">
<solid android:color="#color/sheet_gray"/>
<corners android:radius="24dp" />
</shape>
And this is my BottomSheetDialog :
<androidx.constraintlayout.widget.ConstraintLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/bs_bottomsheet"
android:background="#drawable/bottom_sheet_b"
app:behavior_hideable="false"
app:behavior_peekHeight="40dp"
app:layout_behavior="com.google.android.material.bottomsheet.BottomSheetBehavior">
This will solve all the headaches about:
Setting a custom style and whatnot...
Wondering about how to round the corners in EXPANDED state
etc...
I found out the answer after hours of searching. i only needed to use below style
<style name="AppBottomSheetDialogTheme" parent="Theme.Design.Light.BottomSheetDialog">
<item name="android:windowIsFloating">false</item>
<item name="android:statusBarColor">#android:color/transparent</item>
<item name="android:windowSoftInputMode">adjustResize</item>
<item name="bottomSheetStyle">#style/AppModalStyle</item>
</style>
<style name="AppModalStyle" parent="Widget.Design.BottomSheet.Modal">
<item name="android:background">#drawable/bottom_sheet_background</item>
</style>
<style name="BottomSheetStyle" parent="Theme.Design.BottomSheetDialog">
<item name="bottomSheetStyle">#style/Model</item>
</style>
<style name="Model" parent="Widget.Design.BottomNavigationView">
<item name="background">#drawable/bottom_sheet_layout</item>
</style>

Make the LayoutView as Circle while ending the ScaleAnimation in Android?

I'm creating an animation in View. After the user click button that become as circle. I'm using Scale animation to archive this. but my view layout radius change after click the button. how can i keep the same radius during the animation or are they anyway to achieve this without libraries ?
view xml
<View
android:id="#+id/containerView"
android:layout_width="363dp"
android:layout_height="45dp"
android:layout_marginStart="8dp"
android:layout_marginTop="8dp"
android:layout_marginEnd="8dp"
android:layout_marginBottom="188dp"
android:background="#drawable/login_boader_round"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.333"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="#+id/login_screen_credential_view_holder" />
login_boader_round xml
<?xml version="1.0" encoding="UTF-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android">
<corners
android:pivotX="100%"
android:pivotY="100%"
android:radius="45dp"
/>
<padding
android:bottom="0dp"
android:left="0dp"
android:right="0dp"
android:top="0dp" />
<solid android:color="#677FFF" />
<!--<stroke-->
<!-- android:width="3dp"-->
<!-- android:color="#50A4D1" />-->
</shape>
After the button click event
public void scaleViewAnimation(View view) {
ScaleAnimation scaleAnimation = new ScaleAnimation(1f, 0, 1f, 1f, Animation.RESTART, 0.5f, Animation.RESTART, 0.5f);
scaleAnimation.setDuration(ANIMATION_FADE_DURATION);
scaleAnimation.setFillAfter(true);
view.startAnimation(scaleAnimation);
}
ScaleAnimation class does not have that property. so i used ValueAnimator class to active this. ANIMATION_TIME is an integer. you want to give
ValueAnimator anim = ValueAnimator.ofInt(view.getMeasuredWidth(), view.getMeasuredHeight());
anim.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
#Override
public void onAnimationUpdate(ValueAnimator valueAnimator) {
int val = (Integer) valueAnimator.getAnimatedValue();
ViewGroup.LayoutParams layoutParams = view.getLayoutParams();
layoutParams.width = val;
view.requestLayout();
}
});
anim.setDuration(ANIMATION_TIME);
anim.start();

How can I improve my progress bar match to follow image (color, angle, shape etc.)

I have created a circular progress-bar, and have made it follow as closely as possible to the design in the image below.
But I'm having difficulty having it match the design in the picture below (color, angle, shape etc.):
I don't know how to match :
the color of the above?
or the shape?
Design I'm wanting to follow:
My current design looks like the below:
My code so far is below:
activity_main.xml
<ProgressBar
style="?android:attr/progressBarStyleHorizontal"
android:id="#+id/progressBar"
android:layout_width="240dp"
android:layout_height="240dp"
android:indeterminate="false"
android:max="100"
android:progress="75"
android:progressDrawable="#drawable/style_circular_fill"
android:secondaryProgress="10"
android:layout_alignParentBottom="false"
android:layout_alignParentStart="false"
android:focusableInTouchMode="false"
android:layout_alignParentTop="true"
android:layout_marginTop="70dp"
xmlns:android="http://schemas.android.com/apk/res/android" />
style_circular_fill.xml
<item android:id="#android:id/secondaryProgress">
<rotate
android:fromDegrees="270"
android:pivotX="50%"
android:pivotY="50%"
android:toDegrees="270" >
<shape
android:innerRadiusRatio="2.5"
android:shape="ring"
android:thicknessRatio="20.0"
android:useLevel="true" >
<gradient
android:centerColor="#A9E2F3"
android:endColor="#A9E2F3"
android:startColor="#A9E2F3"
android:type="sweep" />
</shape>
</rotate>
</item>
<item android:id="#android:id/progress">
<rotate
android:fromDegrees="270"
android:pivotX="50%"
android:pivotY="50%"
android:toDegrees="270" >
<shape
android:innerRadiusRatio="2.5"
android:shape="ring"
android:thicknessRatio="20.0"
android:useLevel="true" >
<gradient
android:centerColor="#26ce61"
android:endColor="#26ce61"
android:startColor="#26ce61"
android:type="sweep" />
</shape>
</rotate>
</item>
You could try the CircleProgress library. One of the examples they feature looks quite similar to that of your requirement.
I haven't used it, so cannot confirm the ease of its use.
For the sake of being balanced, check out this list of Progress Bar libraries. There may be a library that can achieve the desired effect.
i suggest that u export the image to the match resources folders (mdpi,hdpi, and so on...);
after that create an animation xml file like this (let's call this file "progress_bar_animation.xml"):
<?xml version="1.0" encoding="utf-8"?>
<rotate xmlns:android="http://schemas.android.com/apk/res/android"
android:drawable="#drawable/your_resource_file_name"
android:pivotX="50%"
android:pivotY="50%"
android:duration="1"
android:fromDegrees="0"
android:toDegrees="1800" />
and then create a progress bar style (in style.xml file)
<style name="ProgressBar" parent="Base.Widget.AppCompat.ProgressBar">
<item name="android:indeterminateDrawable">#drawable/progress_bar_animation</item>
</style>
and finally add a progress bar to your xml and set the style you create before, like this:
<ProgressBar
android:layout_width="wrap_content"
android:layout_height="wrap_content"
style="#style/ProgressBar" />
Use this progress dialogue
public class MyCustomProgressDialog extends ProgressDialog {
private Context c;
private ProgressWheel pd;
private ImageView imgLogo;
public MyCustomProgressDialog(Context context) {
super(context);
getWindow().setBackgroundDrawable(new ColorDrawable(android.graphics.Color.TRANSPARENT));
c=context;
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.progress_bar_loading);
}
#Override
public void show() {
super.show();
}
#Override
public void dismiss() {
super.dismiss();
}
}
progress_bar_loading.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#color/transperent"
android:gravity="center"
>
<TextView
android:id="#+id/lbl_x"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerInParent="true"
android:layout_gravity="center_horizontal"
android:text=" "
android:textColor="#color/white"
android:textSize="20sp"
android:textStyle="bold"/>
<com.organigoal.customcontrol.ProgressWheel
android:id="#+id/progress_wheel"
xmlns:wheel="http://schemas.android.com/apk/res-auto"
android:layout_width="50dp"
android:layout_height="50dp"
android:layout_centerInParent="true"
wheel:barColor="#color/grey"
wheel:progressIndeterminate="true"/>

How to change pressed color to other color of selector dynamically?

that's my selector for list:(item_selector.xml)
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:state_selected="true" android:drawable="#color/orange" />
<item android:state_focused="true" android:drawable="#color/orange" />
<item android:state_pressed="true" android:drawable="#color/orange" />
<item android:drawable="#color/transparent" />
</selector>
that's my row of list(row_item.xml)
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:background="#color/alarm_item_drawer_selector"
>
<ImageView
android:id="#+id/item_icon"
android:layout_width="30dp"
android:layout_height="30dp"
android:layout_centerHorizontal="true"
android:paddingTop="5dp"
android:paddingBottom="2dp"
android:src="#drawable/ic_launcher"/>
<TextView
android:id="#+id/item_title"
style="#style/DrawerItemTextStyle"
android:textColor="#color/text_drawer_item_selector"
android:layout_centerHorizontal="true"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#id/item_icon" />
</RelativeLayout>
I want to change android:state_pressed="true" android:drawable="#color/orange" to other color dynamically. My goal, to make pressed color for each row different. Is it possible to do?
Affect to each item a new StateListDrawable.
StateListDrawable stateListDrawable= new StateListDrawable();
stateListDrawable.addState(new int[] {android.R.attr.state_pressed}, new ColorDrawable(getContext().getResources().getColor(R.color.anycolor)));
stateListDrawable.addState(new int[] {android.R.attr.state_focused}, new ColorDrawable(getContext().getResources().getColor(R.color.anycolor)));
stateListDrawable.addState(new int[] {android.R.attr.state_selected}, new ColorDrawable(getContext().getResources().getColor(R.color.anycolor)));
stateListDrawable.addState(new int[] {}, new ColorDrawable(getContext().getResources().getColor(R.color.anycolor)));
view.setBackgroundDrawable(stateListDrawable);
What I did in a project of mine was I created a static method that takes any view, and changes its background to one of six different colour selectors I made. The trick here is not trying to change the listview selector, you want to change the background of the parent layout of your listview's layout.
Here's an example:
listview.xml (The actual content of the listview)
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/parent"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textColor="#android:color/white"
android:id="#+id/text"
android:text="Text"
android:padding="20dp"/>
</LinearLayout>
getView() method in my adapter:
#Override
public View getView(int i, View view, ViewGroup viewGroup) {
Holder holder = new Holder();
if (view == null) {
LayoutInflater inflater = LayoutInflater.from(context);
view = inflater.inflate(R.layout.listview, viewGroup, false);
} else {
holder = (Holder) view.getTag();
}
holder.parent = (LinearLayout) view.findViewById(R.id.parent);
setRandomListViewSelector(holder.parent);
holder.text = (TextView) view.findViewById(R.id.text);
holder.text.setText(strs.get(i));
return view;
}
Static method that changes the background:
public static void setRandomListViewSelector(View parentView) {
int i = new Random().nextInt(2);
switch (i) {
case 0:
parentView.setBackgroundResource(R.drawable.list_selector_blue);
break;
case 1:
parentView.setBackgroundResource(R.drawable.list_selector_red);
break;
}
}
list_selector_blue.xml
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:state_pressed="true">
<shape>
<solid android:color="#android:color/holo_blue_dark"/>
</shape>
</item>
</selector>
In my example, I just use the Random class to randomly generate a number between 0 and 1. If you'd like more control, you could create a global variable and increment that by 1 so that you have better control over what background colours are set.
If you want to change it dynamically you will have to do it by code. For that you will have to use onTouchListener since you want to know when you touch and release on your view.
final TextView textView =findViewById(R.id.item_title);
textView.setOnTouchListener(new View.OnTouchListener()
{
#Override
public boolean onTouch(View view, MotionEvent motionEvent)
{
switch (motionEvent.getAction()){
case MotionEvent.ACTION_DOWN:
textView.setTextColor(Color.RED);
break;
case MotionEvent.ACTION_UP:case MotionEvent.ACTION_CANCEL:
textView.setTextColor(Color.BLACK);
break;
}
return false;
}
});
The above code will change the text color of your textview when you press it. Change Color.RED to your desired color
Selector tag has type StateListDrawable. Indexing items start at zero. There is a kotlin sample (tested on Android 8.1)
val listDrawable = relativeLayout.background as StateListDrawable
val stateDrawable = listDrawable.getStateDrawable(2) as GradientDrawable // android:state_pressed="true" android:drawable="#color/orange"
stateDrawable.setColor(0xff00ff00)
// or stateDrawable.setColor(Color.parseColor("#00ff00")
// or stateDrawable.setColor(Color.GREEN)

I use TransitionDrawable to change background color but it occure error - NullPointerException

I use following java code to run this,
public class MainActivity extends ActionBarActivity {
int transitionTime = 300;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
TransitionDrawable transition = (TransitionDrawable) findViewById(R.id.relativeLayoutMain).getBackground();
transition.startTransition(transitionTime);
}
Please help me to sole this problem.
Hi I'm new to android and what I'm try to do is change layout background color continuously.
Above method trigger error to me, I not found solution to this but I use different approach to do this.
I use timer with TransitionDrawable and here is my working copy of code.
Here I add "drawable" resources,
transition_drawable.xml (this is main resource xml set this resource file to your layer backbround)
<?xml version="1.0" encoding="UTF-8"?>
<transition xmlns:android="http://schemas.android.com/apk/res/android">
<!-- The drawables used here can be solid colors, gradients, shapes, images, etc. -->
<item android:drawable="#drawable/color_selector_01" />
<item android:drawable="#drawable/color_selector_02" />
</transition>
color_selector_01.xml
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item>
<shape>
<gradient
android:angle="90"
android:startColor="#919bfa"
android:endColor="#4e5bda"
android:type="linear" />
</shape>
</item>
</selector>
color_selector_02.xml
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item>
<shape>
<gradient
android:angle="90"
android:startColor="#fe5528"
android:endColor="#3c1ed4"
android:type="linear" />
</shape>
</item>
</selector>
In my main layout I set layer background to "transition_drawable"
here is my "activity_main.xml"
<ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:fillViewport="true"
android:background="#drawable/transition_drawable" >
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:gravity="center"
android:orientation="horizontal" >
<TextView
android:id="#+id/linkTerms"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:clickable="true"
android:singleLine="true"
android:text="#string/linkTerms" />
<TextView
android:id="#+id/and"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:singleLine="true"
android:text="#string/and" />
<TextView
android:id="#+id/linkPrivacy"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:clickable="true"
android:text="#string/linkPrivacy" />
</LinearLayout>
</ScrollView>
Finlay here is my MainActivity.java file
#TargetApi(Build.VERSION_CODES.HONEYCOMB) #SuppressLint("NewApi") public class MainActivity extends ActionBarActivity {
int transitionTime = 6000;
private RelativeLayout Rlayout;
private TransitionDrawable trans;
final Handler handler_interact=new Handler();//not defined as final variable. may cause problem
View layout_interact;
#SuppressLint("NewApi") #Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
layout_interact =(View) findViewById(R.id.relativeLayoutMain);
Rlayout = (RelativeLayout)findViewById(R.id.relativeLayoutMain);
Resources res = this.getResources();
trans = (TransitionDrawable)res.getDrawable(R.drawable.transition_drawable);
Rlayout.setBackgroundDrawable(trans);
BackgroundColoerChangerCallTimer();
}
public void BackgroundColoerChangerCallTimer(){
//creating timer
Timer timer_interact=new Timer();
timer_interact.schedule(new TimerTask() {
#Override
public void run() {
UpdateGUI();
}
}, 3000);
}
private void UpdateGUI() {
handler_interact.post(runnable_interact);
}
//creating runnable
final Runnable runnable_interact = new Runnable() {
public void run() {
//ayout_interact.setBackgroundColor(Color.GREEN);
trans.reverseTransition(transitionTime);
BackgroundColoerChangerCallTimer();
}
};

Categories