Skip to content

Instantly share code, notes, and snippets.

@masadchattha
Last active June 30, 2020 15:58
Show Gist options
  • Save masadchattha/940c799d6d4ea06b481b9670af63fa0f to your computer and use it in GitHub Desktop.
Save masadchattha/940c799d6d4ea06b481b9670af63fa0f to your computer and use it in GitHub Desktop.
Reuse Drawable java file for Android article on medium.com
package com.asadchattha.reusedrawable;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.content.ContextCompat;
import android.graphics.drawable.GradientDrawable;
import android.os.Bundle;
import android.view.View;
import android.widget.TextView;
import android.widget.Toast;
import java.util.Random;
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
/**
* Handle click events for button(Change Color)
*/
public void onClickButton(View view) {
// Return random number between 1 to 3
int randomNumber = new Random().nextInt(3)+1;
updateDisplay(randomNumber);
}
/**
* Update TextView background color (according to given input)
* by changing color of {@link circle.xml} drawable
*/
private void updateDisplay(int number){
// Find the TextView with view ID number_textView
TextView numberTextView = findViewById(R.id.number_textView);
// Display the current random number in TextView
numberTextView.setText(String.valueOf(number));
// Set the proper background color on the number circle.
// Fetch the background from the TextView, which is a GradientDrawable.
GradientDrawable numberCircle = (GradientDrawable) numberTextView.getBackground();
// Get the appropriate background color based on the current number
int numberColor = getNumberColor(number);
// Set the color on the magnitude circle
numberCircle.setColor(numberColor);
}
/**
* Return the color for the number circle based on the input number.
*
* @param randomly generated number
*/
private int getNumberColor(int number) {
int numberColorResourceId;
int magnitudeFloor = (int) Math.floor(number);
switch (magnitudeFloor) {
case 0:
case 1:
numberColorResourceId = R.color.number1;
break;
case 2:
numberColorResourceId = R.color.number2;
break;
case 3:
numberColorResourceId = R.color.number3;
break;
default:
numberColorResourceId = R.color.number_default;
break;
}
return ContextCompat.getColor(MainActivity.this, numberColorResourceId);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment