Set imageview foreground gradient color programmatically - java

I have xml gradient drawable resource file here:
file: fg_graidient
<shape xmlns:android="http://schemas.android.com/apk/res/android" android:shape="rectangle" >
<gradient
android:type="linear"
android:centerX="0%"
android:startColor="#00020321"
android:centerColor="#F2000000"
android:endColor="#B2020321"
android:angle="45"/>
</shape>
I can the imageview foreground like below:
<ImageView
android:id="#+id/backimg"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:scaleType="fitXY"
android:foreground="#drawable/fg_graidient"
/>
But I want to set this drawable foreground for imageview programmatically. Is it possible?

Create programmatically gradient shapes
ShapeDrawable.ShaderFactory sf = new ShapeDrawable.ShaderFactory() {
#Override
public Shader resize(int width, int height) {
LinearGradient lg = new LinearGradient(0, 0, width, height,
new int[]{Color.GREEN, Color.GREEN, Color.WHITE, Color.WHITE},
new float[]{0,0.5f,.55f,1}, Shader.TileMode.REPEAT);
return lg;
}
};
PaintDrawable p=new PaintDrawable();
p.setShape(new RectShape());
p.setShaderFactory(sf);
use
Button btn= (Button)findViewById(R.id.btn);
btn.setBackgroundDrawable((Drawable)p);

Try this snipet:
ImageView img = (ImageView)findViewById(R.id.backimg);
img.setImageResource(R.drawable.fg_graidient);

Related

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();

Creating a fixed size circle view in android studio

So I have a bit of a frustrating one for me. What I would like to achieve is essentially a button that has two textviews in the center of it. One with a name and one with a number value to it... Like a counter...
I would like it to look like this:
There is a thin white border around it (which given it's colour isn't exactly visible... sorry).
What I'd like to do is have the value increment and decrement depending on how the button is pressed.
Now I have the following so far:
attrs.xml
<resources>
<declare-styleable name="ButtonCounter">
<attr name="backgroundColor" format="color"/>
<attr name="borderColor" format="color"/>
<attr name="borderSize" format="integer"/>
<attr name="labelNameColor" format="color"/>
<attr name="labelValueColor" format="color"/>
<attr name="labelName" format="string"></attr>
<attr name="labelValue" format="string"></attr>
</declare-styleable>
ButtonCounter.java
public class ButtonCounter extends View {
private int backgroundColor,
borderColor,
borderSize,
labelNameColor,
labelValueColor;
private String labelName,
labelValue;
private Paint paintCircle,
paintStroke;
public ButtonCounter(Context context, AttributeSet attrs) {
super(context);
paintCircle = new Paint();
paintStroke = new Paint();
TypedArray a = context.getTheme().obtainStyledAttributes(
attrs,
R.styleable.ButtonCounter
,
0,
0
);
try {
backgroundColor = a.getInteger(R.styleable.ButtonCounter_backgroundColor, 0);
borderColor = a.getInteger(R.styleable.ButtonCounter_borderColor, 0);
borderSize = a.getInteger(R.styleable.ButtonCounter_borderSize, 0);
labelNameColor = a.getInteger(R.styleable.ButtonCounter_labelNameColor,0);
labelValueColor = a.getInteger(R.styleable.ButtonCounter_labelValueColor, 0 );
labelName = a.getString(R.styleable.ButtonCounter_labelName);
labelValue = a.getString(R.styleable.ButtonCounter_labelValue);
} finally {
a.recycle();
}
}
#Override
protected void onDraw(Canvas canvas) {
paintCircle.setColor(backgroundColor);
paintCircle.setAntiAlias(true);
paintStroke.setColor(borderColor);
paintStroke.setAntiAlias(true);
int width = this.getMeasuredWidth();
int height = this.getMeasuredHeight();
int diameter = ((height > width) ? height : width);
int radius = diameter / 2;
canvas.drawCircle(diameter / 2, diameter / 2, radius - borderSize, paintCircle);
canvas.drawCircle(diameter / 2, diameter / 2, radius, paintStroke);
}
}
This doesn't do what I want it to already as it becomes way too big.
Any ideas on how I could start attempting this?
Thanks!
Hi If you want to achieve the same without using Java Class then see the below solution:
Create a drawable with any name lets circle_bg_xml
<shape xmlns:android="http://schemas.android.com/apk/res/android"
android:shape="oval">
<solid android:color="#color/black" />
</shape>
Now in your layout use put two TextViews(or any view) inside LinearLayout and set that drawable as Layout background.
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_width="100dp"
android:layout_height="100dp"
android:gravity="center"
android:background="#drawable/circle_bg">
<TextView
android:layout_width="wrap_content"
android:textColor="#color/white"
android:textSize="15sp"
android:layout_height="wrap_content"
android:text="Global"/>
<TextView
android:layout_width="wrap_content"
android:textColor="#color/white"
android:textSize="22sp"
android:layout_height="wrap_content"
android:text="0"/>
</LinearLayout>
Hope it will help you.
Thanks

How to draw circle in android by pressing a button?

I want to show small dots on screen while pressing a button, something like pin code...
switch (view.getId()){
case R.id.buttonNum1:
editor.putString("PinNumbers",getString(R.string.numberOne));
int x = 10;
int y = 30;
int r = 100;
Paint mPaint = new Paint();
mPaint.setColor(Color.BLACK);
Canvas mCanvas = new Canvas();
mCanvas.drawCircle(x,y,r,mPaint);
break;
You can achive by creating ripple effect
create one drawable name like pin_button_ripple in drawable-v21 folder and add bellow code
<ripple xmlns:android="http://schemas.android.com/apk/res/android"
android:color="?android:colorControlHighlight">
<item android:id="#android:id/mask">
<shape android:shape="oval">
<solid android:color="?android:colorPrimary" />
</shape>
</item>
</ripple>
Now in Layout file set it as a background of button and define click listener in activity
<Button
android:id="#+id/btnPinButton"
android:layout_width="100dp"
android:layout_height="100dp"
android:layout_centerInParent="true"
android:background="#drawable/pin_button_ripple"
android:padding="20dp"
android:text="10"/>
You will see the ripple effect in circle shape like we enter Pin
number or password via keyboard and showing that effect

Dynamic GradientDrawable in RemoteView

I'm having trouble setting a dynamic background for my widget:
My preferences return a color selected by the user and I would like to apply it to the widget but with a gradient effect. So here's where I am at this moment:
My widget.xml:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/widget_layout"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:background="#drawable/style_widget"
> ...
My Service.java:
public void onStart(Intent intent, int startId) {
super.onStart(intent, startId);
remoteViews = new RemoteViews(this.getPackageName(), R.layout.widget);
this.prefs = PreferenceManager.getDefaultSharedPreferences(this);
//this is where I get the color preference value, and create another with some transparency
int color1 = prefs.getInt("background_color", 00000000);
int color2 = Color.argb(22, Color.red(color1), Color.green(color1), Color.blue(color1));
int colors[] = { color1, color2 };
//Create the GradientDrawable:
GradientDrawable gradientDrawable = new GradientDrawable(
GradientDrawable.Orientation.TOP_BOTTOM, colors);
If I do :
remoteViews.setInt(R.id.widget_layout, "setBackgroundColor", color1);
I get the background color changed, but since gradientDrawable isn't an int, how do I apply it to my background via remoteViews?
Well, I've found the answer here:
Setting GradientDrawable through RemoteView
I created an Imageview filling the whole widget, then created a bitmap using my gradientDrawable, then setted the bitmap to the imageview:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/widget_layout"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:background="#drawable/style_widget"
android:padding="0dip" >
<ImageView
android:id="#+id/bck_image"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:scaleType="fitXY"
/>
and then in my Service:
GradientDrawable gradientDrawable = new GradientDrawable(
GradientDrawable.Orientation.LEFT_RIGHT, colors);
float dpi = getBaseContext().getResources().getDisplayMetrics().xdpi;
float dp = getBaseContext().getResources().getDisplayMetrics().density;
Bitmap bitmap = Bitmap.createBitmap(Math.round(288 * dp), Math.round(72 * dp), Config.ARGB_8888);
Canvas canvas = new Canvas(bitmap);
gradientDrawable.setBounds(0, 0, canvas.getWidth(), canvas.getHeight());
gradientDrawable.setCornerRadius(5 * (dpi/160));
gradientDrawable.draw(canvas);
remoteViews.setImageViewBitmap(R.id.bck_image, bitmap);
(I'm very new to Android so I don't know if the code is well formed but for me it works, in case it can help anyone.)

android button with double border and gradient

I want to create a custom button.
This button should have a gradient and a two pixel border, but the inner and outer edge should be in a different color (example: inner is red and outer is yellow).
My question: how do I program the double border (like in the image)?!
Image:
I tried with an XML file with two strokes, but it doesn't work.
I could do this with a 9png file, but I want to do it with pure coding.
btn_bg.xml
<?xml version="1.0" encoding="utf-8"?>
<layer-list xmlns:android="http://schemas.android.com/apk/res/android">
<item >
<shape android:shape="rectangle">
<padding android:left="3.5px"
android:top="3.5px"
android:right="3.5px"
android:bottom="3.5px"/>
<solid android:color="#d4e23a"/>
</shape>
</item>
<item >
<shape android:shape="rectangle">
<padding android:left="4.5px"
android:top="4.5px"
android:right="4.5px"
android:bottom="4.5px"/>
<solid android:color="#d4413a"/>
</shape>
</item>
<item >
<shape android:shape="rectangle">
<gradient android:startColor="#37c325"
android:endColor="#2573c3"
android:angle="-90"/>
</shape>
</item>
</layer-list>
set the above xml as button background.
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text=""
android:background="#drawable/btn_bg"
android:gravity="center"
android:padding="10dp"
android:textStyle="bold"
>
</Button>
Result:
If you want to go by plain Java code then you need to create a class which extends the button, write all your logic in
public void onDraw(Canvas iCanvas).
I have pasted small code snippet from one of my project. Give it a try. thought I have not created the gradient, I have used plain colors.
public class MyButton extends Button {
private Paint m_paint1 = new Paint();
private Paint m_paint2 = new Paint();
private int m_color1 = 0XFF92C84D; // LIKE AN OLIVE GREEN..
private int m_color2 = 0XFFFF0000; // LIKE AN OLIVE GREEN..
private RectF innerRect1, innerRect2;
public MyButton(Context context) {
super(context);
setBackgroundColor(Color.BLACK);
}
public void onDraw(Canvas iCanvas) {
// draw the button background
m_paint1.setColor(m_color1);
m_paint2.setColor(m_color2);
innerRect1 = new RectF(5, 5, getWidth() - 5, getHeight() - 5);
innerRect2 = new RectF(10, 10, getWidth() - 10, getHeight() - 10);
iCanvas.drawRoundRect(innerRect1, 0, 0, m_paint1);
iCanvas.drawRoundRect(innerRect2, 0, 0, m_paint2);
}
public static RelativeLayout.LayoutParams GetRelativeParam(int iLeft,
int iTop, int iWidth, int iHeight) {
RelativeLayout.LayoutParams params = new RelativeLayout.LayoutParams(
iHeight, iWidth);
params.leftMargin = iLeft;
params.topMargin = iTop;
return params;
}
}
and
RelativeLayout relLay = new RelativeLayout(this);
MyButton m_button = new MyButton(this);
setContentView(relLay);
relLay.addView(m_button, MyButton.GetRelativeParam(0, 0, 100, 500));
Put the button inside a layout that you will create just for it. So set to the layout the outest background color that you want.

Categories