Set shape color programmatically - android

I am using keyboard view where i have custom xml shape thath i can set specific buttons a color here is my shape xml:
<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android">
<solid android:color="#80B3B3B3"/>
<corners android:bottomRightRadius="2dp" android:bottomLeftRadius="2dp"
android:topLeftRadius="2dp" android:topRightRadius="2dp"/>
</shape>
Then I overwrite my onDraw method for Keyboard View:
#Override
public void onDraw(Canvas canvas)
{
super.onDraw(canvas);
List<Key> keys = getKeyboard().getKeys();
for (Key key : keys) {
Drawable dr = (Drawable)this.getResources().getDrawable(R.drawable.keyshape);
dr.setBounds(key.x, key.y, key.x + key.width, key.y + key.height);
dr.draw(canvas);
}
}
Now I want to allow that user set this color of Shape any idea how can I set this before drawing?

First of all, you should do a custom view that you want to set and extend it (TextView or Button w/e I will write sample as extending View) since you are not able to edit shape xml programmatically, you will create it as a whole.
Override needed behaviours and constructors for your View. Now you will create a method setGradientColors that take two colours as int values (bottom and top gradient colors). You can modify it for setting radius for rounded corners as well.
public class GradientView extends View{
public GradientView(Context context) {
super(context);
// TODO Auto-generated constructor stub
}
public GradientView(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
// TODO Auto-generated constructor stub
}
public GradientView(Context context, AttributeSet attrs) {
super(context, attrs);
// TODO Auto-generated constructor stub
}
public void setGradientColors(int bottomColor, int topColor) {
GradientDrawable gradient = new GradientDrawable(Orientation.BOTTOM_TOP, new int[] {bottomColor, topColor});
gradient.setShape(GradientDrawable.RECTANGLE);
gradient.setCornerRadius(10.f);
this.setBackgroundDrawable(gradient);
}
}
You are going to use this new view and set shape programmatically as:
GradientView view = (GradientView) findViewById(R.id.customView);
// bottom color - top color order
view.setGradientColors(Color.parseColor("#ff0000"), Color.parseColor("#0000ff"));
If you need further assistance and full explanation about basics, I have achieved this in my project by following this Link
Hope it is going to help you as well.

You can't change shape colour pro grammatically either you have to create new shape with different colour or you can use :
imageView.getBackground().setColorFilter(Color.parseColor("#BBBDBF"), Mode.MULTIPLY);
imageview.invalidate();
it will multiply the given colour code with your image background and will show effect of colour changed.

If you want change only the colors on the shape from the xml drawable, I changed your onDraw a little to do it.
It will be a GradientDrawable if you define it in xml with <shape> tag.
Drawable dr = this.getResources().getDrawable(R.drawable.keyshape);
if (dr instanceof GradientDrawable) {
GradientDrawable gradientDr = (GradientDrawable) dr;
gradientDr.setBounds(key.x, key.y, key.x + key.width, key.y + key.height);
gradientDr.setColor(Color.GREEN);
gradientDr.draw(canvas);
}

Related

How to set a views shape and background color programatically?

I have to create a circle shape and paint it randomly but I have to do it programmatically.
It has to be look like
this
TextView that needs background
val tvAuthorSubtext = TextView(context)
tvAuthorSubtext.apply {
text = "AA"
textSize = 10f
setTextColor(ContextCompat.getColor(context, R.color.white))
gravity = Gravity.CENTER
typeface = ResourcesCompat.getFont(context, R.font.ubuntu)
layoutParams = LinearLayout.LayoutParams(72, 72)
setBackgroundResource(R.drawable.bg_author_shape)
}
R.drawable.bg_author_shape
<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android">
<corners android:radius="12dp" />
<solid android:color="#color/black" />
</shape>
getBackgroundRandomColor Function
fun getRandomBackgroundColor() :Int {
val colorArray : MutableList<Int> = mutableListOf()
colorArray.add(R.color.aqua)
colorArray.add(R.color.bright_blue)
colorArray.add(R.color.bright_purple)
colorArray.add(R.color.bright_pink)
colorArray.add(R.color.bright_green)
colorArray.add(R.color.orangey_yellow)
colorArray.add(R.color.tealish)
val rnds = (0..(colorArray.size-1)).random()
return colorArray[rnds]
}
Is there any way to run functions in drawable xmls?
Is there any way to change shape drawable background color without changing its shape
You can't change the background color of your drawable shape in xml.
For dynamically changing the color of your shape you have to create custom views.
I came up with these two approaches :
Approach Number 1 :
Creating Custom View using Canvas And Paint.
Here is an useful example of how to create Circle shape programmatically and assign color to it.
Creating CustomView using Canvas And Paint
you can also draw Text when drawing your shape on onDraw() method.
Approach Number 2 :
Creating Custom View by extending The View or other ViewGroup Classes.
Here is a simple sample of the way you should doing it.
public class ColorOptionsView extends View {
private View mValue;
private ImageView mImage;
public ColorOptionsView(Context context, AttributeSet attrs) {
super(context, attrs);
TypedArray a = context.obtainStyledAttributes(attrs,
R.styleable.Options, 0, 0);
String titleText = a.getString(R.styleable.Options_titleText);
int valueColor = a.getColor(R.styleable.Options_valueColor,
android.R.color.holo_blue_light);
a.recycle();
// more stuff
}
}

Android: programmatically created image vs resource image

1) Is it possible to create drawable, example
static Bitmap.Config conf = Bitmap.Config.ARGB_8888;
static Bitmap bmp = Bitmap.createBitmap(100, 100, conf);
// something draw
// eventually convert to DrawableBitmap
and then convert it / asiggn as / put in resource, to use in function with resource id param, like:
public void setWidgetLayoutResource (int widgetLayoutResId)
or
2) is it possible to dynamically draw to change image in R.drawable.something.bmp?
All this for change color of widget in setWidgetLayoutResource() to any color, not fixed as color of concrete resource
My own answer
This question is relative to my other: Android PreferenceScreen
and I was do it in this way:
ColorLinesView.java
public class ColorLinesView extends View
{
private static GradientDrawable gdDefault = new GradientDrawable();
public static int fillColor;
public ColorLinesView(Context context, AttributeSet attrs)
{ super(context, attrs);
}
#Override protected void onDraw(Canvas cv)
{
gdDefault.setColor(fillColor);
gdDefault.setCornerRadius(4);
gdDefault.setStroke(2, 0xffbbbbbb);
this.setBackgroundDrawable(gdDefault);
}
}
color_lines_accesory.xml
<?xml version="1.0" encoding="utf-8"?>
<android.swp.ColorLinesView xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/colorBoxLines"
android:layout_width="52dp"
android:layout_height="26dp"
android:gravity="right"
android:layout_marginRight="6dp" />
and finally while programmatically create PreferenceScreen, after add category preference "somePref":
ColorLinesView.fillColor = 0xff00ff00; // examply green
somePref.setWidgetLayoutResource(R.layout.color_lines_accesory);
and the same two lines (with new color) in OnPreferenceClickListener() for "somePref" category, after using color picker to change color.
result:

How to set strike line of text view with red color in Android [duplicate]

This question already has an answer here:
How to change color of a strikethrough in android? [duplicate]
(1 answer)
Closed 7 years ago.
Using this code I am able to display text view with strike to textView :
holder.discounttext.setText("MRP " + rupee + discountcost);
holder.discounttext.setPaintFlags(holder.discounttext.getPaintFlags() | Paint.STRIKE_THRU_TEXT_FLAG);
This is my Current Screen :
Desire Screen:
Please tell me how to set strike color with red?
Make a custom TextView
class CustomTextView extends TextView {
public Paint paint;
public boolean addStrike = false;
public CustomTextView(Context context, AttributeSet attrs) {
super(context, attrs);
}
public CustomTextView(Context context) {
super(context);
init(context);
}
public CustomTextView(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
init(context);
}
private void init(Context context) {
paint = new Paint();
paint.setColor(Color.RED);
paint.setStrokeWidth(getResources().getDisplayMetrics().density * 1);
}
#Override
protected void onDraw(Canvas canvas) {
// TODO Auto-generated method stub
super.onDraw(canvas);
if (addStrike) {
canvas.drawLine(0, getHeight() / 2, getWidth(),
getHeight() / 2, paint);
}
}
}
for adding stoke you can call
myCustomTextView.addStrike = true;
myCustomTextView.invalidate();
and for removing strike you just call
myCustomTextView.addStrike = false;
myCustomTextView.invalidate();
The easiest way is to use Drawable. The idea is to create a line drawable, and then set the background of TextView with this drawable. Let the Drawable file be line.xml
<item android:state_pressed="false">
<shape android:shape="line">
<stroke android:width="2dp"
android:color="#ffffff" />
</shape>
</item>
This is the drawable for the line with red color, and 2dp width. [Alter it according to your requirements]
Then on the TextView, set the line.xml drawable as background.
holder.discounttext.setBackground(getResources().getDrawable(R.drawable.line));
The output will be
A couple of solutions:
subclass textview and draw your own strike through. See create different color strike through.
overlay another view on top of it.

how to change image as long as button is pressed... and then showing default on button unpress android

I want to change imageview's image when user is holding button and change the image back to the default when user releases button.
Use OnFocusChangeListener(view) method & override OnFocusChange() method to this.
You need to use XML Selectors for this. You can specify whatever drawable you want for whatever state you want.
The docs are here: http://developer.android.com/reference/android/graphics/drawable/StateListDrawable.html
You will create an XML, that has references to each of the states you want to apply styles to, then you will reference when you assign a drawable to a view (a button for instance), instead of a particular drawable.
Check this SO question for more details: Android selector & text color
You can set an OnTouchListener to the ImageView and in the OnTouchListener you can set the image you want to display in MotionEvent.ACTION_DOWN and revert the old image in MotionEvent.ACTION_UP.
You can create a custom Button class like this
public class MButton extends Button {
public MButton(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
// TODO Auto-generated constructor stub
}
public MButton(Context context, AttributeSet attrs) {
super(context, attrs);
// TODO Auto-generated constructor stub
}
public MButton(Context context) {
super(context);
// TODO Auto-generated constructor stub
}
// define style
/**
* Send resource ids for normal, selected, pressed in respective order
*
* #param mImageIds
*/
public void setDrawablePressedBg(Integer... mImageIds) {
StateListDrawable bg = new StateListDrawable();
Drawable normal = this.getResources().getDrawable(mImageIds[0]);
Drawable selected = this.getResources().getDrawable(mImageIds[1]);
Drawable pressed = this.getResources().getDrawable(mImageIds[2]);
bg.addState(View.PRESSED_ENABLED_STATE_SET, pressed);
bg.addState(View.ENABLED_FOCUSED_STATE_SET, selected);
bg.addState(View.ENABLED_STATE_SET, normal);
bg.addState(View.FOCUSED_STATE_SET, selected);
bg.addState(View.EMPTY_STATE_SET, normal);
this.setBackgroundDrawable(bg);
}
// define style
public void setBackgroundPressedBg(Integer p1, Integer p2, Integer p3) {
StateListDrawable bg = new StateListDrawable();
Drawable normal = this.getResources().getDrawable(p1);
Drawable selected = this.getResources().getDrawable(p2);
Drawable pressed = this.getResources().getDrawable(p3);
bg.addState(View.PRESSED_ENABLED_STATE_SET, pressed);
bg.addState(View.ENABLED_FOCUSED_STATE_SET, selected);
bg.addState(View.ENABLED_STATE_SET, normal);
bg.addState(View.FOCUSED_STATE_SET, selected);
bg.addState(View.EMPTY_STATE_SET, normal);
this.setBackgroundDrawable(bg);
}
}
And you can use it like this in your onCreate Method
this.book_appointment = (MButton) this._view
.findViewById(R.id.btn_book);
this.book_appointment.setBackgroundPressedBg(R.drawable.btnnormal,
R.drawable.btnsel, R.drawable.btnsel);
This will go like this in your xml layout file
<com.packageName.custom.MButton
android:id="#+id/btn_book"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#id/tv_time1"
android:layout_marginTop="20dp"
android:background="#drawable/bookapointment" />
here in this post you can find the solution:
https://stackoverflow.com/a/18196156/2000517
Take care! ;)

Android Custom Component View w/Rounded Corners

I'm trying to create a View with rounded corners (and a background color of choice) that I can reuse with different background colors; hard to explain, so here's my code:
/app/src/com/packagename/whatever/CustomDrawableView.java
package com.packagename.whatever;
import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.Canvas;
import android.graphics.drawable.PaintDrawable;
import android.util.AttributeSet;
import android.view.View;
public class CustomDrawableView extends View {
private PaintDrawable mDrawable;
int radius;
private void init(AttributeSet attrs) {
TypedArray a = getContext().obtainStyledAttributes(attrs,R.styleable.RoundedRect);
radius = a.getInteger(R.styleable.RoundedRect_radius, 0);
}
public CustomDrawableView(Context context, AttributeSet attrs) {
super(context, attrs);
init(attrs);
mDrawable = new PaintDrawable();
}
protected void onDraw(Canvas canvas) {
mDrawable.setCornerRadius(radius);
mDrawable.draw(canvas);
}
}
Here's the XML to display the custom component:
/app/res/layout/test.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:ny="http://schemas.android.com/apk/res/com.packagename.whatever"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:background="#ffffff"
android:padding="10dp">
<com.packagename.whatever.CustomDrawableView
android:id="#+id/custom"
android:layout_width="200dp"
android:layout_height="200dp"
android:background="#b80010"
ny:radius="50"
/>
</LinearLayout>
I'm wanting the red box to have 50px rounded corners, but as you'll see, it does not:
The idea is that I could easily change the background color in the XML and automatically have a nice View with rounded corners, without having to create multiple drawables.
Thanks for the help!
You need to set your corner radius and color into the background drawable.
Here is one way that would work. Grab the color you set in android:background, then use it to create a new drawable that you set into the background in the constructor. This will work as long as you only set android:background to a color value.
public CustomDrawableView(Context context, AttributeSet attrs) {
super(context, attrs);
init(attrs);
// pull out the background color
int color = attrs.getAttributeIntValue("http://schemas.android.com/apk/res/android", "background", 0xffffffff);
// create a new background drawable, set the color and radius and set it in place
mDrawable = new PaintDrawable();
mDrawable.getPaint().setColor(color);
mDrawable.setCornerRadius(radius);
setBackgroundDrawable(mDrawable);
}
If you override onDraw, make sure you call super.onDraw(canvas) first to get the background drawn.
given a simple shapedrawable like this:
public ShapeDrawable Sd(int s){
float[] outerR = new float[] { 12, 12, 12, 12, 12, 12, 12, 12 };
ShapeDrawable mDrawable = new ShapeDrawable(new RoundRectShape(outerR, null,null));
mDrawable.getPaint().setColor(s);
return mDrawable;
}
you can do the following:
LinearLayout l=(LinearLayout) findViewById(R.id.testLayout);
l.setBackgroundDrawable(Sd(0xff74AC23));
where the 12's represent the radius.
you could apply this to any view for a background drawable.
Take a look at this question: How do I set the rounded corner radius of a color drawable using xml?
And perhaps also these two:
How to add rounded corner to a drawable I'm using as a background in Android?
How should I give images rounded corners in Android?

Categories

Resources