android - How to send and receive local broadcast








MainActivity.java



package com.cfsuman.androidtutorials;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.app.Activity;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;
import androidx.localbroadcastmanager.content.LocalBroadcastManager;
import java.util.Random;


public class MainActivity extends Activity {
private Context mContext;

// Initialize a new BroadcastReceiver instance
private BroadcastReceiver mRandomNumberReceiver
= new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
// Get the received random number
int receivedNumber = intent.getIntExtra(
"RandomNumber",-1);

// Display a notification that the broadcast received
Toast.makeText(
context,
"Received : " + receivedNumber,
Toast.LENGTH_SHORT
).show();
}
};

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);

// Get the context
mContext = getApplicationContext();

// Register the local broadcast
LocalBroadcastManager.getInstance(mContext).registerReceiver(
mRandomNumberReceiver,
new IntentFilter("BROADCAST_RANDOM_NUMBER")
);


// Get the widgets reference from XML layout
Button button = findViewById(R.id.button);
TextView textView = findViewById(R.id.textView);


// Set a click listener for Button widget
button.setOnClickListener(view -> {
// Generate a random number
int randomNumber = new Random().nextInt(500);

// Initialize a new intent instance
Intent intent = new Intent("BROADCAST_RANDOM_NUMBER");
// Put the random number to intent to broadcast it
intent.putExtra("RandomNumber",randomNumber);

// Send the broadcast
LocalBroadcastManager.getInstance(mContext)
.sendBroadcast(intent);

// Update the TextView with random number
textView.setText("Random number generated : "
+ randomNumber
+ "\nApp also broadcast it."
);
});
}
}





activity_main.xml



<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="match_parent"
xmlns:tools="http://schemas.android.com/tools"
android:background="#DCDCDC"
android:padding="24dp">

<Button
android:id="@+id/button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Send Local Broadcast"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />

<TextView
android:id="@+id/textView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:fontFamily="sans-serif"
android:textStyle="italic"
android:textSize="24sp"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="@+id/button"
tools:text="TextView" />

</androidx.constraintlayout.widget.ConstraintLayout>











android - How to rotate a Bitmap on Canvas center








MainActivity.java



package com.cfsuman.androidtutorials;

import android.content.res.Resources;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Matrix;
import android.graphics.Paint;
import android.os.Bundle;
import android.app.Activity;
import android.widget.Button;
import android.widget.ImageView;


public class MainActivity extends Activity {
private Resources mResources;

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);

// Get the Resources
mResources = getResources();

// Get the widgets reference from XML layout
Button button = findViewById(R.id.button);
ImageView imageView = findViewById(R.id.imageView);


// Set a click listener for Button widget
button.setOnClickListener(view -> {
// Get the source bitmap to draw on canvas
Bitmap srcBitmap = BitmapFactory.decodeResource(
mResources,
R.drawable.rose_small
);

// Initialize a new Bitmap
Bitmap bitmap = Bitmap.createBitmap(
1400, // Width
1000, // Height
Bitmap.Config.ARGB_8888 // Config
);

// Initialize a new Canvas instance
Canvas canvas = new Canvas(bitmap);

// Draw a solid color on the canvas as background
canvas.drawColor(Color.LTGRAY);

// Initialize a new Paint instance to draw on canvas
Paint paint = new Paint();
paint.setAntiAlias(true);
paint.setDither(true);
paint.setFilterBitmap(true);

// Initialize a new Matrix instance
Matrix matrix = new Matrix();

// Set rotation on matrix
matrix.setRotate(
45, // degrees
(float) srcBitmap.getWidth() / 2, // px
(float)srcBitmap.getHeight() / 2 // py
);

// Draw the bitmap at the center position of the canvas
// both vertically and horizontally
matrix.postTranslate(
(float) canvas.getWidth() / 2
- (float) srcBitmap.getWidth() / 2, // dx
(float) canvas.getHeight() / 2
- (float) srcBitmap.getHeight() / 2 // dy
);


// Finally, draw the bitmap on canvas as a rotated bitmap
canvas.drawBitmap(
srcBitmap, // Bitmap
matrix, // Matrix
paint // Paint
);

// Display the newly created bitmap on app interface
imageView.setImageBitmap(bitmap);
});
}
}





activity_main.xml



<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#DCDCDC"
android:padding="24dp">

<Button
android:id="@+id/button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Draw"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />

<ImageView
android:id="@+id/imageView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="@+id/button" />

</androidx.constraintlayout.widget.ConstraintLayout>









android - How to rotate a Canvas








MainActivity.java



package com.cfsuman.androidtutorials;

import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.os.Bundle;
import android.app.Activity;
import android.widget.Button;
import android.widget.ImageView;


public class MainActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);

// Get the widgets reference from XML layout
Button button = findViewById(R.id.button);
ImageView imageView = findViewById(R.id.imageView);


// Set a click listener for Button widget
button.setOnClickListener(view -> {
// Initialize a new Bitmap
Bitmap bitmap = Bitmap.createBitmap(
1200, // Width
600, // Height
Bitmap.Config.ARGB_8888 // Config
);

// Initialize a new Canvas instance
Canvas canvas = new Canvas(bitmap);

// Draw a solid color on the canvas as background
canvas.drawColor(Color.LTGRAY);

// Initialize a new Paint instance to draw on canvas
Paint paint = new Paint();
paint.setStyle(Paint.Style.FILL);
paint.setColor(Color.parseColor("#676767"));
paint.setAntiAlias(true);

// Set an offset value in pixels to draw rectangle on canvas
int offset = 200;

// Save the canvas state
canvas.saveLayer(
0, // left
0, // top
canvas.getWidth(),
canvas.getHeight(),
null // paint
);

// Rotate the canvas
canvas.rotate(
25, // degrees
(float) canvas.getWidth() / 2, // px, center x
(float) canvas.getHeight() / 2 // py, center y
);

// Draw the rounded corners rectangle object on the canvas
// The rectangle will be drawn as a 25 degrees rotated rectangle
canvas.drawRect(
offset, // left
offset, // top
canvas.getWidth() - offset, // right
canvas.getHeight() - offset, // bottom
paint // Paint
);

// Finally, restore the canvas state
canvas.restore();

// Display the newly created bitmap on app interface
imageView.setImageBitmap(bitmap);
});
}
}





activity_main.xml



<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#DCDCDC"
android:padding="24dp">

<Button
android:id="@+id/button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Draw"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />

<ImageView
android:id="@+id/imageView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="@+id/button" />

</androidx.constraintlayout.widget.ConstraintLayout>








android - How to draw Rounded Rectangle on Canvas








MainActivity.java



package com.cfsuman.androidtutorials;

import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.RectF;
import android.os.Bundle;
import android.app.Activity;
import android.widget.Button;
import android.widget.ImageView;


public class MainActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);

// Get the widgets reference from XML layout
Button button = findViewById(R.id.button);
ImageView imageView = findViewById(R.id.imageView);


// Set a click listener for Button widget
button.setOnClickListener(view -> {
// Initialize a new Bitmap
Bitmap bitmap = Bitmap.createBitmap(
1200, // Width
600, // Height
Bitmap.Config.ARGB_8888 // Config
);

// Initialize a new Canvas instance
Canvas canvas = new Canvas(bitmap);

// Draw a solid color on the canvas as background
canvas.drawColor(Color.LTGRAY);

// Initialize a new Paint instance to
// draw the rounded rectangle
Paint paint = new Paint();
paint.setStyle(Paint.Style.FILL);
paint.setColor(Color.parseColor("#676767"));
paint.setAntiAlias(true);

// Set an offset value in pixels to draw
// rounded rectangle on canvas
int offset = 75;

// Initialize a new RectF instance
RectF rectF = new RectF(
offset, // left
offset, // top
canvas.getWidth() - offset, // right
canvas.getHeight() - offset // bottom
);

// Define the corners radius of rounded rectangle
int cornersRadius = 50;

// Finally, draw the rounded corners
// rectangle object on the canvas
canvas.drawRoundRect(
rectF, // rect
cornersRadius, // rx
cornersRadius, // ry
paint // Paint
);

// Display the newly created bitmap on app interface
imageView.setImageBitmap(bitmap);
});
}
}





activity_main.xml



<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#DCDCDC"
android:padding="24dp">

<Button
android:id="@+id/button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Draw Rounded Rectangle"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />

<ImageView
android:id="@+id/imageView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="@+id/button" />

</androidx.constraintlayout.widget.ConstraintLayout>










android - How to draw a Bitmap on a Canvas







MainActivity.java



package com.cfsuman.androidtutorials;

import android.content.res.Resources;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Color;
import android.os.Bundle;
import android.app.Activity;
import android.widget.Button;
import android.widget.ImageView;


public class MainActivity extends Activity {
private Resources mResources;

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);

// Get the Resources
mResources = getResources();

// Get the widgets reference from XML layout
Button button = findViewById(R.id.button);
ImageView imageView = findViewById(R.id.imageView);


// Set a click listener for Button widget
button.setOnClickListener(view -> {
// Bitmap to draw on the canvas
Bitmap bitmap = BitmapFactory.decodeResource(
mResources,
R.drawable.flower
);

// Define an offset value between canvas and bitmap
int offset = 100;

// Initialize a new Bitmap to hold the source bitmap
Bitmap dstBitmap = Bitmap.createBitmap(
bitmap.getWidth() + offset * 2, // Width
bitmap.getHeight() + offset * 2, // Height
Bitmap.Config.ARGB_8888 // Config
);

// Initialize a new Canvas instance
Canvas canvas = new Canvas(dstBitmap);

// Draw a solid color on the canvas as background
canvas.drawColor(Color.LTGRAY);

//Finally, Draw the source bitmap on the canvas
canvas.drawBitmap(
bitmap, // Bitmap
offset, // Left
offset, // Top
null // Paint
);

// Display the newly created bitmap on app interface
imageView.setImageBitmap(dstBitmap);
});
}
}




activity_main.xml



<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#DCDCDC"
android:padding="24dp">

<Button
android:id="@+id/button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Draw Bitmap"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />

<ImageView
android:id="@+id/imageView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="@+id/button" />

</androidx.constraintlayout.widget.ConstraintLayout>








android - How to draw a Line on Canvas







MainActivity.java



package com.cfsuman.androidtutorials;

import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.os.Bundle;
import android.app.Activity;
import android.widget.Button;
import android.widget.ImageView;


public class MainActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);

// Get the widgets reference from XML layout
Button button = findViewById(R.id.button);
ImageView imageView = findViewById(R.id.imageView);


// Set a click listener for Button widget
button.setOnClickListener(view -> {
// Initialize a new Bitmap object
Bitmap bitmap = Bitmap.createBitmap(
1200, // Width
600, // Height
Bitmap.Config.ARGB_8888 // Config
);

// Initialize a new Canvas instance
Canvas canvas = new Canvas(bitmap);

// Draw a solid color on the canvas as background
canvas.drawColor(Color.LTGRAY);

// Initialize a new Paint instance to draw the line
Paint paint = new Paint();
// Line color
paint.setColor(Color.parseColor("#676767"));
paint.setStyle(Paint.Style.STROKE);
// Line width in pixels
paint.setStrokeWidth(12);
paint.setAntiAlias(true);

// Set a pixels value to offset the line from canvas edge
int offset = 50;

// Draw a line on canvas at the center position
canvas.drawLine(
offset, // startX
(float) canvas.getHeight() / 2, // startY
canvas.getWidth() - offset, // stopX
(float) canvas.getHeight() / 2, // stopY
paint // Paint
);

// Display the newly created bitmap on app interface
imageView.setImageBitmap(bitmap);
});
}
}





activity_main.xml



<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#DCDCDC"
android:padding="24dp">

<Button
android:id="@+id/button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Draw Line"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />

<ImageView
android:id="@+id/imageView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="@+id/button" />

</androidx.constraintlayout.widget.ConstraintLayout>









android - How to draw a Rectangle on a Canvas







MainActivity.java



package com.cfsuman.androidtutorials;

import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Rect;
import android.os.Bundle;
import android.app.Activity;
import android.widget.Button;
import android.widget.ImageView;


public class MainActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);

// Get the widgets reference from XML layout
Button button = findViewById(R.id.button);
ImageView imageView = findViewById(R.id.imageView);


// Set a click listener for Button widget
button.setOnClickListener(view -> {
// Initialize a new Bitmap object
Bitmap bitmap = Bitmap.createBitmap(
1200, // Width
600, // Height
Bitmap.Config.ARGB_8888 // Config
);

// Initialize a new Canvas instance
Canvas canvas = new Canvas(bitmap);

// Draw a solid color to the canvas background
canvas.drawColor(Color.LTGRAY);

// Initialize a new Paint instance to draw the Rectangle
Paint paint = new Paint();
paint.setStyle(Paint.Style.FILL);
paint.setColor(Color.parseColor("#676767"));
paint.setAntiAlias(true);

// Set a pixels value to padding around the rectangle
int padding = 50;

// Initialize a new Rect object
Rect rectangle = new Rect(
padding, // Left
padding, // Top
canvas.getWidth() - padding, // Right
canvas.getHeight() - padding // Bottom
);

// Finally, draw the rectangle on the canvas
canvas.drawRect(rectangle,paint);

// Display the newly created bitmap on app interface
imageView.setImageBitmap(bitmap);
});
}
}





activity_main.xml



<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#DCDCDC"
android:padding="24dp">

<Button
android:id="@+id/button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Draw Rectangle"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />

<ImageView
android:id="@+id/imageView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="@+id/button" />

</androidx.constraintlayout.widget.ConstraintLayout>








android - How to draw a circle on a Canvas







MainActivity.java



package com.cfsuman.androidtutorials;

import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.os.Bundle;
import android.app.Activity;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;


public class MainActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);

// Get the widgets reference from XML layout
Button button = findViewById(R.id.button);
ImageView imageView = findViewById(R.id.imageView);


// Set a click listener for Button widget
button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
// Initialize a new Bitmap object
Bitmap bitmap = Bitmap.createBitmap(
1200, // Width
600, // Height
Bitmap.Config.ARGB_8888 // Config
);

// Initialize a new Canvas instance
Canvas canvas = new Canvas(bitmap);

// Draw a solid color to the canvas background
canvas.drawColor(Color.LTGRAY);

// Initialize a new Paint instance to draw the Circle
Paint paint = new Paint();
paint.setStyle(Paint.Style.FILL);
paint.setColor(Color.RED);
paint.setAntiAlias(true);

// Calculate the available radius of canvas
int radius = Math.min(
canvas.getWidth(),canvas.getHeight()/2);

// Set a pixels value to padding around the circle
int padding = 5;

// Finally, draw the circle on the canvas
canvas.drawCircle(
(float)canvas.getWidth() / 2, // cx
(float)canvas.getHeight() / 2, // cy
radius - padding, // Radius
paint // Paint
);

// Display the newly created bitmap on app interface
imageView.setImageBitmap(bitmap);
}
});
}
}





activity_main.xml



<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#DCDCDC"
android:padding="24dp">

<Button
android:id="@+id/button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Draw Circle"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />

<ImageView
android:id="@+id/imageView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="@+id/button" />

</androidx.constraintlayout.widget.ConstraintLayout>











android - Draw border and shadow around a bitmap






activity_main.xml



<androidx.constraintlayout.widget.ConstraintLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#FFF"
android:padding="24dp"
tools:context=".MainActivity">

<Button
android:id="@+id/button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Draw Border"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />

<ImageView
android:id="@+id/iv"
android:layout_width="0dp"
android:layout_height="250dp"
android:layout_marginTop="24dp"
android:scaleType="fitCenter"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="@+id/button" />

</androidx.constraintlayout.widget.ConstraintLayout>




MainActivity.java



package com.cfsuman.androidtutorials;

import android.content.Context;
import android.content.res.Resources;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Rect;
import android.os.Bundle;
import android.app.Activity;
import android.widget.Button;
import android.widget.ImageView;


public class MainActivity extends Activity {
private ImageView mImageView;
private Context mContext;
private Resources mResources;
private Bitmap mBitmap;

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);

// Get the application context
mContext = getApplicationContext();

// Get the Resources
mResources = getResources();

// Get the widgets reference from XML layout
Button btn = findViewById(R.id.button);
mImageView = findViewById(R.id.iv);

// Get the bitmap resource id
final int bitmapResourceID =R.drawable.flower;

// Set an image to ImageView
mImageView.setImageBitmap(
BitmapFactory.decodeResource(
mResources, bitmapResourceID
)
);

btn.setOnClickListener(v -> {
// Get the bitmap from drawable resources
mBitmap = BitmapFactory.decodeResource(
mResources, bitmapResourceID
);

// Add a border around the bitmap
mBitmap = addBorderToBitmap(
mBitmap, 50,
Color.parseColor("#F0F8FF")
);

// Add a border around the bitmap as shadow
mBitmap = addBorderToBitmap(
mBitmap, 10,
Color.LTGRAY
);

// Set the ImageView image as drawable object
mImageView.setImageBitmap(mBitmap);
});
}


// Custom method to add a border around bitmap
protected Bitmap addBorderToBitmap(
Bitmap srcBitmap, int borderWidth, int borderColor){

// Initialize a new Bitmap to make it bordered bitmap
Bitmap dstBitmap = Bitmap.createBitmap(
srcBitmap.getWidth() + borderWidth*2, // Width
srcBitmap.getHeight() + borderWidth*2, // Height
Bitmap.Config.ARGB_8888 // Config
);

// Initialize a new Canvas instance
Canvas canvas = new Canvas(dstBitmap);

// Initialize a new Paint instance to draw border
Paint paint = new Paint();
paint.setColor(borderColor);
paint.setStyle(Paint.Style.STROKE);
paint.setStrokeWidth(borderWidth);
paint.setAntiAlias(true);

Rect rect = new Rect(
borderWidth / 2,
borderWidth / 2,
canvas.getWidth() - borderWidth / 2,
canvas.getHeight() - borderWidth / 2
);

// Draw a rectangle as a border/shadow on canvas
canvas.drawRect(rect,paint);

// Draw source bitmap to canvas
canvas.drawBitmap(
srcBitmap, borderWidth, borderWidth, null
);

srcBitmap.recycle();

// Return the bordered bitmap
return dstBitmap;
}
}








android - How to create rounded corners ImageView






activity_main.xml



<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:padding="24dp"
tools:context=".MainActivity"
android:background="#F8F8FF">

<Button
android:id="@+id/btn"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Rounded It"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />

<ImageView
android:id="@+id/iv"
android:layout_width="match_parent"
android:layout_height="250dp"
android:layout_marginTop="24dp"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="@+id/btn" />

</androidx.constraintlayout.widget.ConstraintLayout>






MainActivity.java



package com.cfsuman.androidtutorials;

import android.app.Activity;
import android.content.Context;
import android.content.res.Resources;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.widget.Button;
import android.widget.ImageView;
import androidx.core.graphics.drawable.RoundedBitmapDrawable;
import androidx.core.graphics.drawable.RoundedBitmapDrawableFactory;


public class MainActivity extends Activity {
private Context mContext;
private Resources mResources;
private Button mBTN;
private ImageView mImageView;
private Bitmap mBitmap;

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);

// Get the application context
mContext = getApplicationContext();

// Get the Resources
mResources = getResources();

// Get the widgets reference from XML layout
mImageView = (ImageView) findViewById(R.id.iv);
mBTN = (Button) findViewById(R.id.btn);

// Get the bitmap from drawable resources
mBitmap = BitmapFactory.decodeResource(
mResources,
R.drawable.flower
);

// Display the bitmap in ImageView
mImageView.setImageBitmap(mBitmap);

// Set a click listener for Button widget
mBTN.setOnClickListener(view -> {
// Define the ImageView corners radius
float cornerRadius = 80.0f;

// Initialize a new RoundedBitmapDrawable
RoundedBitmapDrawable roundedBitmapDrawable
= RoundedBitmapDrawableFactory.create(
mResources,
mBitmap
);

// Set the RoundedBitmapDrawable corners radius
roundedBitmapDrawable.setCornerRadius(cornerRadius);

roundedBitmapDrawable.setAntiAlias(true);

// Set the ImageView image as drawable object
mImageView.setImageDrawable(roundedBitmapDrawable);
});
}
}










android - How to save image to file in external storage






activity_main.xml



<androidx.constraintlayout.widget.ConstraintLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#F8F8FF"
android:padding="16dp"
tools:context=".MainActivity">

<Button
android:id="@+id/button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Save Image To External Storage"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />

<ImageView
android:id="@+id/ivSource"
android:layout_width="0dp"
android:layout_height="200dp"
android:layout_marginTop="12dp"
android:src="@drawable/flower3"
android:scaleType="centerCrop"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="@+id/button" />

<TextView
android:id="@+id/tvSource"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="8dp"
android:text="Original Image"
app:layout_constraintStart_toStartOf="@+id/ivSource"
app:layout_constraintTop_toBottomOf="@+id/ivSource" />

<ImageView
android:id="@+id/ivSaved"
android:layout_width="0dp"
android:layout_height="200dp"
android:layout_marginTop="48dp"
android:scaleType="centerCrop"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="@+id/tvSource" />

<TextView
android:id="@+id/tvSaved"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="8dp"
app:layout_constraintStart_toStartOf="@+id/ivSaved"
app:layout_constraintTop_toBottomOf="@+id/ivSaved" />

</androidx.constraintlayout.widget.ConstraintLayout>






MainActivity.java



package com.cfsuman.androidtutorials;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.net.Uri;
import android.os.Bundle;
import android.app.Activity;
import android.os.Environment;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
import androidx.core.content.ContextCompat;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;


public class MainActivity extends Activity {
private ImageView mIvSaved;
private TextView mTvSaved;
private Context mContext;

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);

// Get the application context
mContext = getApplicationContext();

// Get the widgets reference from XML layout
Button btn = findViewById(R.id.button);
mIvSaved = findViewById(R.id.ivSaved);
mTvSaved = findViewById(R.id.tvSaved);

btn.setOnClickListener(v -> {
// Get the image from drawable
// resource as drawable object
Drawable drawable = ContextCompat.getDrawable(
mContext, R.drawable.flower3
);

// Get the bitmap from drawable object
//assert drawable != null;
Bitmap bitmap = ((BitmapDrawable) drawable)
.getBitmap();

// Initializing a new file
File file;

// Get the external storage directory path
String path = Environment.getExternalStorageDirectory()
.toString();

// Create a file to save the image
file = new File(path, "UniqueFileName" + ".jpg");

try {
OutputStream stream = null;
stream = new FileOutputStream(file);
bitmap.compress(
Bitmap.CompressFormat.JPEG,
100, stream
);
stream.flush();
stream.close();

} catch (IOException e) // Catch the exception
{
e.printStackTrace();
}

// Parse the saved image path to uri
Uri savedImageURI = Uri.parse(file.getAbsolutePath());

// Display the saved image to ImageView
mIvSaved.setImageURI(savedImageURI);

// Display saved image uri to TextView
mTvSaved.setText(
"Image saved in external storage.\n"
+ savedImageURI
);
});
}
}



AndroidManifest.xml [permission]



<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>








android - How to save an image to gallery






activity_main.xml



<androidx.constraintlayout.widget.ConstraintLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#F8F8FF"
android:padding="16dp"
tools:context=".MainActivity">

<Button
android:id="@+id/button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Save Image To Gallery"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />

<ImageView
android:id="@+id/ivSource"
android:layout_width="0dp"
android:layout_height="200dp"
android:layout_marginTop="12dp"
android:src="@drawable/flower4"
android:scaleType="centerCrop"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="@+id/button" />

<TextView
android:id="@+id/tvSource"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="8dp"
android:text="Original Image"
app:layout_constraintStart_toStartOf="@+id/ivSource"
app:layout_constraintTop_toBottomOf="@+id/ivSource" />

<ImageView
android:id="@+id/ivSaved"
android:layout_width="0dp"
android:layout_height="200dp"
android:layout_marginTop="48dp"
android:scaleType="centerCrop"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="@+id/tvSource" />

<TextView
android:id="@+id/tvSaved"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="8dp"
app:layout_constraintStart_toStartOf="@+id/ivSaved"
app:layout_constraintTop_toBottomOf="@+id/ivSaved" />

</androidx.constraintlayout.widget.ConstraintLayout>






MainActivity.java



package com.cfsuman.androidtutorials;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.net.Uri;
import android.os.Bundle;
import android.app.Activity;
import android.provider.MediaStore;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
import androidx.core.content.ContextCompat;


public class MainActivity extends Activity {
private ImageView mIvSaved;
private TextView mTvSaved;
private Context mContext;

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);

// Get the application context
mContext = getApplicationContext();

// Get the widgets reference from XML layout
Button btn = findViewById(R.id.button);
mIvSaved = findViewById(R.id.ivSaved);
mTvSaved = findViewById(R.id.tvSaved);

btn.setOnClickListener(v -> {
// Get the image from drawable
// resource as drawable object
Drawable drawable = ContextCompat.getDrawable(
mContext,R.drawable.flower4
);

// Get the bitmap from drawable object
//assert drawable != null;
Bitmap bitmap = ((BitmapDrawable)drawable)
.getBitmap();

// Save image to gallery
String savedImageURL = MediaStore.Images.Media
.insertImage(
getContentResolver(),
bitmap,
"flower",
"Image of flower"
);

// Parse the gallery image url to uri
Uri savedImageURI = Uri.parse(savedImageURL);

// Display the saved image to ImageView
mIvSaved.setImageURI(savedImageURI);

// Display saved image url to TextView
mTvSaved.setText(
"Image saved to gallery.\n" + savedImageURL
);
});
}
}



AndroidManifest.xml [permission]



<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>








android - How to take ScreenShot programmatically






activity_main.xml



<androidx.constraintlayout.widget.ConstraintLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:padding="24dp"
android:id="@+id/rootLayout"
tools:context=".MainActivity"
android:background="#DCDCDC">

<Button
android:id="@+id/button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Take ScreenShot"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />

<ImageView
android:id="@+id/imageView"
android:layout_width="0dp"
android:layout_height="0dp"
android:layout_marginTop="16dp"
android:scaleType="centerCrop"
android:src="@drawable/flower7"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="@+id/button" />

</androidx.constraintlayout.widget.ConstraintLayout>





MainActivity.java



package com.cfsuman.androidtutorials;

import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.os.Bundle;
import android.app.Activity;
import android.provider.MediaStore;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;
import androidx.constraintlayout.widget.ConstraintLayout;


public class MainActivity extends Activity {

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);

// Get the widgets reference from XML layout
Button button = findViewById(R.id.button);
ConstraintLayout rootLayout = findViewById(R.id.rootLayout);

button.setOnClickListener(view -> {
// Take the screenshot
Bitmap screenShot = TakeScreenShot(rootLayout);

// Save the screenshot on device gallery
MediaStore.Images.Media.insertImage(
getContentResolver(),
screenShot,
"Image",
"Captured ScreenShot"
);

// Notify the user that screenshot taken.
Toast.makeText(
getApplicationContext(),
"Screen Captured.",
Toast.LENGTH_SHORT
).show();
});
}


// Custom method to take screenshot
public Bitmap TakeScreenShot(View rootView){
// Screenshot taken for the specified root
// view and its child elements.
Bitmap bitmap = Bitmap.createBitmap(
rootView.getWidth(),
rootView.getHeight(),
Bitmap.Config.ARGB_8888
);
Canvas canvas = new Canvas(bitmap);
rootView.draw(canvas);
return bitmap;
}
}



AndroidManifest.xml [permission]



<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>









android - How to change ActionBar title programmatically








MainActivity.java



package com.cfsuman.androidtutorials;

import android.os.Bundle;
import android.widget.Button;
import androidx.appcompat.app.ActionBar;
import androidx.appcompat.app.AppCompatActivity;


public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);

// Get the widgets reference from XML layout
Button button = findViewById(R.id.button);


// Set the button click listener
button.setOnClickListener(view -> {
// Get the ActionBar
ActionBar actionBar = getSupportActionBar();

// Change the ActionBar title text
assert actionBar != null;
actionBar.setTitle("Updated ActionBar Title");
});
}
}





activity_main.xml



<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#DCDCDC"
android:padding="24dp">

<Button
android:id="@+id/button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Change ActionBar Title Text"
android:textAllCaps="false"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />

</androidx.constraintlayout.widget.ConstraintLayout>









How to show an indeterminate ProgressBar in Android








MainActivity.java



package com.cfsuman.androidtutorials;

import android.os.Bundle;
import android.app.Activity;
import android.os.Handler;
import android.view.View;
import android.widget.Button;
import android.widget.ProgressBar;
import android.widget.TextView;


public class MainActivity extends Activity {
private int progressStatus = 0;
private Handler handler = new Handler();

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);

// Get the widgets reference from XML layout
Button button = findViewById(R.id.button);
ProgressBar progressBar = findViewById(R.id.progressBar);
TextView textView = findViewById(R.id.textView);


// Set a click listener for Button widget
button.setOnClickListener(view -> {
// Disable the button itself
view.setEnabled(false);

// Set the progress status zero on each button click
progressStatus = 0;
// Visible the progress bar and text view
progressBar.setVisibility(View.VISIBLE);
textView.setVisibility(View.VISIBLE);

// Start the lengthy operation in a background thread
new Thread(new Runnable() {
@Override
public void run() {
while (progressStatus < 100) {
// Update the progress status
progressStatus += 1;

// Try to sleep the thread for 20 milliseconds
try {
Thread.sleep(100);
} catch (InterruptedException e) {
e.printStackTrace();
}

// Update the progress bar
handler.post(new Runnable() {
@Override
public void run() {
progressBar.setProgress(progressStatus);
// Show the progress on TextView
textView.setText(progressStatus + "");
// If task execution completed
if (progressStatus == 100) {
// Hide the progress bar from layout
// after finishing task
progressBar.setVisibility(View.GONE);
// Set a message of completion
textView.setText("Operation completed.");

// Enable the button itself
view.setEnabled(true);
}
}
});
}
}
}).start(); // Start the operation
});
}
}





activity_main.xml



<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="match_parent"
xmlns:tools="http://schemas.android.com/tools"
android:background="#DCDCDC"
android:padding="24dp">

<TextView
android:id="@+id/textView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="64dp"
android:fontFamily="sans-serif"
android:textSize="24sp"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
tools:text="TextView" />

<ProgressBar
android:id="@+id/progressBar"
style="@android:style/Widget.Holo.Light.ProgressBar.Horizontal"
android:visibility="gone"
android:indeterminate="true"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_below="@id/textView"
android:layout_marginTop="16dp"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="@+id/textView" />

<Button
android:id="@+id/button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="24dp"
android:text="Start Task"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="@+id/progressBar" />

</androidx.constraintlayout.widget.ConstraintLayout>










How to create a ProgressBar programmatically in Android


Create a ProgressBar In Code




ProgressBar is used to indicate the progress of an operation or long-running task, so the user can get a visual idea of how much time it will take to finish the job. We can simply add a ProgressBar widget to our XML layout file but when android developers want to put a ProgressBar in their app interface is a little bit harder. This android app development tutorial will guide you on how you can add a ProgressBar widget to your app rapidly in java code.




In the first step, we will create a ProgressBar in Java code. After that, we will set its layout parameters and define relative layout rules, and put it to relative layout on a specific location. The relative layout addView method allows us to add a dynamic view to it.




In the second step, we will show the operation progress in our newly added ProgressBar after a button click event. This is a determinate progress bar, so we can simply show the progress percentage in our widget. We also applied a color filter on our programmatically created ProgressBar widget.




The operation run on a background thread, so the app user interface is not blocked by the long-running task. We run an example task using runnable and handler in this tutorial. Button click starts the operation and the handler runs it periodically and completes it on time.




activity_main.xml



<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/rl"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:padding="10dp"
tools:context=".MainActivity"
android:background="#d6e6de"
>
<Button
android:id="@+id/btn"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Create ProgressBar"
/>
<Button
android:id="@+id/btn_start"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Start Operation"
android:layout_toRightOf="@id/btn"
/>
<TextView
android:id="@+id/tv"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="@id/btn_start"
/>
</RelativeLayout>





MainActivity.java



package com.cfsuman.me.androidcodesnippets;

import android.graphics.Color;
import android.graphics.PorterDuff;
import android.os.Bundle;
import android.app.Activity;
import android.view.View;
import android.widget.Button;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.ProgressBar;
import android.os.Handler;
import android.widget.RelativeLayout.LayoutParams;


public class MainActivity extends Activity {
private int progressStatus = 0;
private Handler handler = new Handler();
ProgressBar pb;

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);

// Get the widgets reference from XML layout
final RelativeLayout rl = (RelativeLayout) findViewById(R.id.rl);
final Button btn = (Button) findViewById(R.id.btn);
final Button btn_start = (Button) findViewById(R.id.btn_start);
final TextView tv = (TextView) findViewById(R.id.tv);

btn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
//ProgressBar(Context context, AttributeSet attrs, int defStyleAttr)
// Initialize a new Progressbar instance
// Create a new progress bar programmatically
pb = new ProgressBar(getApplicationContext(), null, android.R.attr.progressBarStyleHorizontal);

// Create new layout parameters for progress bar
LayoutParams lp = new LayoutParams(
550, // Width in pixels
LayoutParams.WRAP_CONTENT // Height of progress bar
);

// Apply the layout parameters for progress bar
pb.setLayoutParams(lp);

// Get the progress bar layout parameters
LayoutParams params = (LayoutParams) pb.getLayoutParams();

// Set a layout position rule for progress bar
params.addRule(RelativeLayout.BELOW, tv.getId());

// Apply the layout rule for progress bar
pb.setLayoutParams(params);

// Set the progress bar color
pb.getProgressDrawable().setColorFilter(Color.BLUE, PorterDuff.Mode.SRC_IN);

// Finally, add the progress bar to layout
rl.addView(pb);
}
});

btn_start.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
// Set the progress status zero on each button click
progressStatus = 0;
// Start the lengthy operation in a background thread
new Thread(new Runnable() {
@Override
public void run() {
while(progressStatus < 100){
// Update the progress status
progressStatus +=1;

// Try to sleep the thread for 20 milliseconds
try{
Thread.sleep(20);
}catch(InterruptedException e){
e.printStackTrace();
}

// Update the progress bar
handler.post(new Runnable() {
@Override
public void run() {
pb.setProgress(progressStatus);
// Show the progress on TextView
tv.setText(progressStatus+"");
}
});
}
}
}).start(); // Start the operation
}
});
}
}













How to change ProgressBar color programmatically in Android








MainActivity.java



package com.cfsuman.androidtutorials;

import android.graphics.Color;
import android.graphics.PorterDuff;
import android.os.Bundle;
import android.app.Activity;
import android.os.Handler;
import android.widget.Button;
import android.widget.ProgressBar;
import android.widget.TextView;


public class MainActivity extends Activity {
private int progressStatus = 0;
private Handler handler = new Handler();

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);

// Get the widgets reference from XML layout
Button button = findViewById(R.id.button);
ProgressBar pbDefault = findViewById(R.id.pbDefault);
ProgressBar pbColored = findViewById(R.id.pbColored);
TextView tvProgress = findViewById(R.id.tvProgress);


// Change the default color of progress bar programmatically
pbColored.getProgressDrawable()
.setColorFilter(Color.RED, PorterDuff.Mode.SRC_IN);


// Set a click listener for Button widget
button.setOnClickListener(view -> {
// Disable the button itself
view.setEnabled(false);

// Set the progress status zero on each button click
progressStatus = 0;

// Start the lengthy operation in a background thread
new Thread(new Runnable() {
@Override
public void run() {
while(progressStatus < 100){
// Update the progress status
progressStatus +=1;

// Try to sleep the thread for 20 milliseconds
try{
Thread.sleep(100);
}catch(InterruptedException e){
e.printStackTrace();
}

// Update the progress bar
handler.post(new Runnable() {
@Override
public void run() {
pbDefault.setProgress(progressStatus);
pbColored.setProgress(progressStatus);
// Show the progress on TextView
tvProgress.setText(progressStatus+"");
}
});
}
}
}).start(); // Start the operation
});
}
}





activity_main.xml



<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="match_parent"
xmlns:tools="http://schemas.android.com/tools"
android:background="#DCDCDC"
android:padding="24dp">

<TextView
android:id="@+id/tvProgress"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginStart="32dp"
android:layout_marginTop="48dp"
android:fontFamily="sans-serif"
android:textSize="24sp"
android:textStyle="bold"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
tools:text="TextView" />

<ProgressBar
android:id="@+id/pbDefault"
style="@android:style/Widget.Holo.Light.ProgressBar.Horizontal"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_below="@id/tvProgress"
android:layout_marginTop="16dp"
android:layout_marginEnd="8dp"
app:layout_constraintEnd_toStartOf="@+id/tvDefault"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="@+id/tvProgress" />

<TextView
android:id="@+id/tvDefault"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:fontFamily="sans-serif"
android:textSize="16sp"
android:textStyle="italic"
app:layout_constraintBottom_toBottomOf="@+id/pbDefault"
app:layout_constraintEnd_toEndOf="parent"
android:text="Default Color" />

<ProgressBar
android:id="@+id/pbColored"
style="@android:style/Widget.Holo.Light.ProgressBar.Horizontal"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_below="@id/tvProgress"
android:layout_marginTop="16dp"
android:layout_marginEnd="8dp"
app:layout_constraintEnd_toStartOf="@+id/tvColored"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="@+id/pbDefault" />

<TextView
android:id="@+id/tvColored"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:fontFamily="sans-serif"
android:textSize="16sp"
android:textStyle="italic"
app:layout_constraintBottom_toBottomOf="@+id/pbColored"
app:layout_constraintEnd_toEndOf="parent"
android:text="Custom Color" />

<Button
android:id="@+id/button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="24dp"
android:text="Start"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="@+id/pbColored" />

</androidx.constraintlayout.widget.ConstraintLayout>