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>








Android horizontal ProgressBar example








MainActivity.java



package com.cfsuman.androidtutorials;

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

// 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+"");
}
});
}
}
}).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"
android:textStyle="bold"
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: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"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="@+id/progressBar" />

</androidx.constraintlayout.widget.ConstraintLayout>










How to set ImageView width and height programmatically in Android


Set ImageView Width & Height Programmatically



ImageView widget allows us to display an image object to the android app user interface. We can add an ImageView element to the app interface by putting an ImageView tag inside the XML layout file. Then we can define the image source of the ImageView widget. We also can set the ImageView width and height in the XML layout file using ImageView layout width and height attributes. This is an easy task.




But sometimes android app developers need to change the Imageview size (height and width) using their java or kotlin scripting file. This is called programmatically changing ImageView height and width in an android application. This android app development tutorial demonstrates to you how can we change the ImageView width and height dynamically in an android application.




To do that, at first we will put an ImageView widget to our XML layout file. We will wrap our ImageView widget with a constraint layout. We will also add a Button widget to the XML layout file. This Button widget’s click event will dynamically change the ImageView width and height.




Inside the Button click event, we will define the ImageView new width and height. Then we call ImageView requestLayout() method to invalidate the layout. Then, we will call ImageView getLayoutParams() method and apply the new width and height of it. Finally, we will specify the ImageView image scale type, so that the image will display perfectly inside the ImageView widget.




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="Set ImageView New Width, Height"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />

<ImageView
android:id="@+id/iv"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="24dp"
android:src="@drawable/flower"
android:background="#DCDCDC"
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.os.Bundle;
import android.widget.Button;
import android.widget.ImageView;


public class MainActivity extends Activity {
private ImageView mImageView;

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

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


// Set a click listener for Button widget
mBTN.setOnClickListener(view -> {
int newHeight = 200; // New height in pixels
int newWidth = 300; // New width in pixels

/*
requestLayout()
Call this when something has changed which has
invalidated the layout of this view.
*/
mImageView.requestLayout();

/*
getLayoutParams()
Get the LayoutParams associated with this view.
*/

// Apply the new height for ImageView programmatically
mImageView.getLayoutParams().height = newHeight;

// Apply the new width for ImageView programmatically
mImageView.getLayoutParams().width = newWidth;

// Set the scale type for ImageView image scaling
mImageView.setScaleType(ImageView.ScaleType.FIT_XY);
});
}
}








How to create an ImageView programmatically in Android


Create An ImageView Programmatically




The ImageView element displays an image to its visible area. Android app developers can simply add an ImageView tag and available attributes to their XML layout file to show an ImageView to the android app user interface. In this XML layout file, they can set the ImageView image source by using its src attribute. This is a simple job.




But sometimes, android app developers want to add an ImageView widget programmatically to their android application. So they have to write a few lines of code to their java or kotlin programming file to achieve this. This android app development tutorial will demonstrate to us how can we add an ImageView widget to our android application dynamically and set an image source to display it.




Though the following code snippets are very clear to understand the full scenario, we will describe here the code. To add an ImageView programmatically to the layout we first add a relative layout in the XML layout file. Then we will put a Button widget inside it. On the Button click event, we will add the ImageView inside the relative layout programmatically.




Inside the Button click event, we will call ImageView() method to create an instance of a new ImageView widget. Then we will call Imageview setImageDrawable() method to add a drawable image source to the ImageView widget.




After that, we will create a LayoutParams object to define the newly created ImageView layout parameters such as width and height. In this layout parameters object, we will add a rule to put ImageView widget below of Button widget inside the relative layout. Then we will apply this layout parameters object to the ImageView widget.




Finally, we add the newly created ImageView object to the relative layout using the addView() method. Now our android app will create an ImageView programmatically on the Button click event and display an image on it.



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="#bfbbb1"
>
<Button
android:id="@+id/btn"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Create ImageView"
/>
</RelativeLayout>





MainActivity.java



package com.cfsuman.androidtutorials;

import android.os.Bundle;
import android.app.Activity;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.RelativeLayout.LayoutParams;
import androidx.core.content.ContextCompat;


public class MainActivity extends Activity {

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

// Get the context
MainActivity context = this;

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

btn.setOnClickListener(view -> {
// Initialize a new ImageView widget
ImageView iv = new ImageView(getApplicationContext());

// Set an image for ImageView
iv.setImageDrawable(
ContextCompat.getDrawable(
context,
R.drawable.flower_small
)
);

// Create layout parameters for ImageView
LayoutParams lp = new LayoutParams(
LayoutParams.WRAP_CONTENT,
LayoutParams.WRAP_CONTENT
);

// Add rule to layout parameters
// Add the ImageView below to Button
lp.addRule(RelativeLayout.BELOW, btn.getId());

// Add layout parameters to ImageView
iv.setLayoutParams(lp);

// Finally, add the ImageView to layout
rl.addView(iv);
});
}
}








How to set a bitmap to ImageView in Android






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="#DCDCDC"
android:padding="24dp"
tools:context=".MainActivity">

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

<ImageView
android:id="@+id/iv"
android:layout_width="0dp"
android:layout_height="0dp"
android:layout_marginTop="16dp"
android:scaleType="centerCrop"
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.BitmapFactory;
import android.os.Bundle;
import android.app.Activity;
import android.widget.Button;
import android.widget.ImageView;


public class MainActivity extends Activity {
private ImageView mImageView;

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

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

btn.setOnClickListener(v -> {
Bitmap bitmap = BitmapFactory.decodeResource(
getResources(),R.drawable.flower6
);

// Set ImageView image as a Bitmap
mImageView.setImageBitmap(bitmap);
});
}
}









How to set ImageView image from Assets in Android






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="#DCDCDC"
android:padding="24dp"
tools:context=".MainActivity">

<Button
android:id="@+id/button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Set ImageView Image From Assets"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />

<ImageView
android:id="@+id/iv"
android:layout_width="0dp"
android:layout_height="0dp"
android:layout_marginTop="16dp"
android:scaleType="centerCrop"
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.content.res.AssetManager;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.app.Activity;
import android.widget.Button;
import android.widget.ImageView;
import java.io.IOException;
import java.io.InputStream;


public class MainActivity extends Activity {
private ImageView mImageView;

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

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

// String variable to hold specified image file name
final String imageFileName = "flower101.jpg";

btn.setOnClickListener(v -> {
// Set ImageView image from drawable resource
mImageView.setImageBitmap(
getBitmapFromAssets(imageFileName)
);
});
}


// Custom method to get assets folder image as bitmap
private Bitmap getBitmapFromAssets(String fileName){
AssetManager am = getAssets();
InputStream is = null;
try{
is = am.open(fileName);
}catch(IOException e){
e.printStackTrace();
}

return BitmapFactory.decodeStream(is);
}
}








How to set ImageView image from drawable in Android






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="#DCDCDC"
android:padding="24dp"
tools:context=".MainActivity">

<Button
android:id="@+id/button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Set ImageView Image"
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="16dp"
android:scaleType="centerCrop"
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.os.Bundle;
import android.app.Activity;
import android.widget.Button;
import android.widget.ImageView;
import androidx.core.content.ContextCompat;


public class MainActivity extends Activity {
private ImageView mImageView;

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

// Get the context
MainActivity context = this;

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

btn.setOnClickListener(v -> {
// Set ImageView image from drawable resource
mImageView.setImageDrawable(
ContextCompat.getDrawable(
context,
R.drawable.flower7
)
);
});
}
}








How to set ImageView image from URL in Android






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="#DCDCDC"
android:padding="24dp"
tools:context=".MainActivity">

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

<ImageView
android:id="@+id/iv"
android:layout_width="0dp"
android:layout_height="0dp"
android:layout_marginTop="16dp"
android:scaleType="centerCrop"
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.BitmapFactory;
import android.os.AsyncTask;
import android.os.Bundle;
import android.app.Activity;
import android.widget.Button;
import android.widget.ImageView;
import java.io.InputStream;
import java.net.URL;


public class MainActivity extends Activity {
private ImageView mImageView;

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

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

final String imgURL = "https://images.pexels.com/photos/" +
"1337332/pexels-photo-1337332.jpeg";

btn.setOnClickListener(v -> {
new DownLoadImageTask(mImageView).execute(imgURL);
});
}


private class DownLoadImageTask extends AsyncTask<String,Void,Bitmap> {
ImageView imageView;

public DownLoadImageTask(ImageView imageView){
this.imageView = imageView;
}

protected Bitmap doInBackground(String...urls){
String urlOfImage = urls[0];
Bitmap logo = null;
try{
InputStream is = new URL(urlOfImage)
.openStream();
logo = BitmapFactory.decodeStream(is);
}catch(Exception e){ // Catch the download exception
e.printStackTrace();
}
return logo;
}

protected void onPostExecute(Bitmap result){
imageView.setImageBitmap(result);
}
}
}








How to programmatically set image to ImageView in Android






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="#DCDCDC">

<ImageView
android:id="@+id/iv"
android:layout_width="match_parent"
android:layout_height="wrap_content"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"/>

</androidx.constraintlayout.widget.ConstraintLayout>





MainActivity.java



package com.cfsuman.androidtutorials;

import android.app.Activity;
import android.os.Bundle;
import android.widget.ImageView;


public class MainActivity extends Activity {
private ImageView mImageView;

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

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

/*
public void setImageResource (int resId)
Sets a drawable as the content of this ImageView.

Related XML Attributes
android:src

Parameters
resId : the resource identifier of the drawable
*/

// Set the ImageView image programmatically
mImageView.setImageResource(R.drawable.flower5);
}
}






How to set an image to ImageView in XML in Android






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="#F0F8FF">

<!--
ImageView
Displays an arbitrary image, such as an icon.
The ImageView class can load images from various sources.
-->

<!--
android:src
Sets a drawable as the content of this ImageView.

May be a reference to another resource,
in the form "@[+][package:]type:name"
or to a theme attribute in the form "?[package:][type:]name".

May be a color value, in the form of "#rgb", "#argb",
"#rrggbb", or "#aarrggbb".

This corresponds to the global attribute resource symbol src.
-->

<!-- Set ImageView image in XML layout -->
<ImageView
android:id="@+id/iv"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:src="@drawable/flower6"
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 set an image to ImageView in Android






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="#d8dcda"
android:padding="24dp"
tools:context=".MainActivity">

<!-- Set ImageView image by XML-->
<ImageView
android:id="@+id/ivXML"
android:layout_width="match_parent"
android:layout_height="150dp"
android:src="@drawable/flower"
android:scaleType="centerCrop"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />

<!-- Set ImageView image programmatically-->
<ImageView
android:id="@+id/ivResource"
android:layout_width="match_parent"
android:layout_height="150dp"
android:layout_marginTop="8dp"
android:scaleType="centerCrop"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="@+id/ivXML" />

<!-- Set ImageView image as drawable programmatically-->
<ImageView
android:id="@+id/ivDrawable"
android:layout_width="match_parent"
android:layout_height="150dp"
android:layout_marginTop="8dp"
android:scaleType="centerCrop"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="@+id/ivResource" />

<!-- Set ImageView image as bitmap programmatically-->
<ImageView
android:id="@+id/ivBitmap"
android:layout_width="match_parent"
android:layout_height="150dp"
android:layout_marginTop="8dp"
android:scaleType="centerCrop"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="@+id/ivDrawable" />

</androidx.constraintlayout.widget.ConstraintLayout>





MainActivity.java



package com.cfsuman.androidtutorials;

import android.os.Bundle;
import android.app.Activity;
import android.widget.ImageView;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import androidx.core.content.ContextCompat;


public class MainActivity extends Activity {

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

// Get the context
MainActivity context = this;

// Get the widgets reference from XML layout
ImageView ivResource = findViewById(R.id.ivResource);
ImageView ivDrawable = findViewById(R.id.ivDrawable);
ImageView ivBitmap = findViewById(R.id.ivBitmap);

// Set image from resource
ivResource.setImageResource(R.drawable.flower2);

// Set image as drawable for third ImageView
ivDrawable.setImageDrawable(
ContextCompat.getDrawable(
context,
R.drawable.flower3
)
);

Bitmap bitmap = BitmapFactory.decodeResource(
getResources(),R.drawable.flower4);

// Set image as bitmap for fourth ImageView
ivBitmap.setImageBitmap(bitmap);
}
}






How to set DatePickerDialog cancel button click listener in Android









MainActivity.java



package com.cfsuman.androidtutorials;

import android.app.DatePickerDialog;
import android.app.Dialog;
import android.content.DialogInterface;
import android.os.Bundle;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.Toast;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.fragment.app.DialogFragment;
import java.util.Calendar;


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


// Show the date picker dialog
button.setOnClickListener(v -> {
// Initialize a new date picker dialog fragment
DialogFragment dialogFragment = new DatePickerFragment();

// Show the date picker dialog fragment
dialogFragment.show(
getSupportFragmentManager(),
"Date Picker"
);
});
}



public static class DatePickerFragment extends DialogFragment
implements DatePickerDialog.OnDateSetListener{

@NonNull
@Override
public Dialog onCreateDialog(Bundle savedInstanceState){
final Calendar calendar = Calendar.getInstance();
int year = calendar.get(Calendar.YEAR);
int month = calendar.get(Calendar.MONTH);
int day = calendar.get(Calendar.DAY_OF_MONTH);

// Return the DatePickerDialog
return new DatePickerDialog(
getActivity(),0, this,year,month,day);
}


public void onDateSet(
DatePicker view, int year, int month, int day){
// Do something with the chosen date
}


public void onCancel(@NonNull DialogInterface dialog){
// Send a message to confirm cancel button click
Toast.makeText(
getActivity(),
"Date Picker Dialog Canceled.",
Toast.LENGTH_SHORT
).show();
}
}
}





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="Show DatePickerDialog"
android:textAllCaps="false"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />

</androidx.constraintlayout.widget.ConstraintLayout>








How to create a custom Title for DatePickerDialog in Android









MainActivity.java



package com.cfsuman.androidtutorials;

import android.app.DatePickerDialog;
import android.app.Dialog;
import android.graphics.Color;
import android.graphics.Typeface;
import android.os.Bundle;
import android.util.TypedValue;
import android.view.Gravity;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.TextView;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.constraintlayout.widget.ConstraintLayout.LayoutParams;
import androidx.fragment.app.DialogFragment;
import java.util.Calendar;


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


// Show the date picker dialog
button.setOnClickListener(v -> {
// Initialize a new date picker dialog fragment
DialogFragment dFragment = new DatePickerFragment();

// Show the date picker dialog fragment
dFragment.show(
getSupportFragmentManager(),
"Date Picker"
);
});
}



public static class DatePickerFragment extends DialogFragment
implements DatePickerDialog.OnDateSetListener{

@NonNull
@Override
public Dialog onCreateDialog(Bundle savedInstanceState){
final Calendar calendar = Calendar.getInstance();
int year = calendar.get(Calendar.YEAR);
int month = calendar.get(Calendar.MONTH);
int day = calendar.get(Calendar.DAY_OF_MONTH);


DatePickerDialog datePickerDialog = new DatePickerDialog(
getActivity(),0,this,year,month,day);


// Create a TextView programmatically.
TextView textView = new TextView(getActivity());


// Create a TextView programmatically
LayoutParams lp = new LayoutParams(
LayoutParams.WRAP_CONTENT, // Width of TextView
LayoutParams.WRAP_CONTENT // Height of TextView
);
textView.setLayoutParams(lp);
textView.setPadding(0, 48, 0, 48);
textView.setGravity(Gravity.CENTER);
textView.setTypeface(Typeface.SANS_SERIF,Typeface.ITALIC);
textView.setTextSize(TypedValue.COMPLEX_UNIT_SP,24);
textView.setText("This is a custom title.");
textView.setTextColor(Color.WHITE);
textView.setBackgroundColor(Color.parseColor("#5DA493"));


// Set the newly created TextView as
// a custom tile of DatePickerDialog
datePickerDialog.setCustomTitle(textView);


// Or you can simply set a tile for DatePickerDialog
// Uncomment this line to activate it
//datePickerDialog.setTitle("This is a simple title.");


// Return the DatePickerDialog
return datePickerDialog;
}

public void onDateSet(
DatePicker view, int year, int month, int day){
// Do something with the chosen date
}
}
}





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="Show DatePickerDialog"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />

</androidx.constraintlayout.widget.ConstraintLayout>







How to set DatePickerDialog max date and min date in Android









MainActivity.java



package com.cfsuman.androidtutorials;

import android.app.DatePickerDialog;
import android.app.Dialog;
import android.os.Bundle;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.TextView;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.fragment.app.DialogFragment;
import java.text.DateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.Locale;


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


// Show the date picker dialog
button.setOnClickListener(v -> {
// Initialize a new date picker dialog fragment
DialogFragment dialogFragment = new DatePickerFragment();

// Show the date picker dialog fragment
dialogFragment.show(
getSupportFragmentManager(),
"Date Picker"
);
});
}



public static class DatePickerFragment extends DialogFragment
implements DatePickerDialog.OnDateSetListener{

@NonNull
@Override
public Dialog onCreateDialog(Bundle savedInstanceState){
final Calendar calendar = Calendar.getInstance();
int year = calendar.get(Calendar.YEAR);
int month = calendar.get(Calendar.MONTH);
int day = calendar.get(Calendar.DAY_OF_MONTH);

DatePickerDialog datePickerDialog = new DatePickerDialog(
getActivity(),
//AlertDialog.THEME_HOLO_LIGHT,
0,
this,year,month,day);

// Add 3 days to Calendar
calendar.add(Calendar.DATE, 3);


// Set the Calendar new date as
// maximum date of date picker
datePickerDialog.getDatePicker().setMaxDate(
calendar.getTimeInMillis());

// Subtract 6 days from Calendar updated date
calendar.add(Calendar.DATE, -6);

// Set the Calendar new date as
// minimum date of date picker
datePickerDialog.getDatePicker().setMinDate(
calendar.getTimeInMillis());

// So, now date picker selectable date
// range is 7 days only
// Return the DatePickerDialog
return datePickerDialog;
}


public void onDateSet(
DatePicker view, int year, int month, int day){

// Get the text view from XML layout
TextView textView = (TextView) requireActivity()
.findViewById(R.id.textView);

// Create a Date variable/object with user chosen date
Calendar cal = Calendar.getInstance();
cal.setTimeInMillis(0);
cal.set(year, month, day, 0, 0, 0);
Date chosenDate = cal.getTime();

// Format the date using style and locale
DateFormat df = DateFormat.getDateInstance(
DateFormat.MEDIUM, Locale.US);
String formattedDate = df.format(chosenDate);

// Display the chosen date to app interface
textView.setText(formattedDate);
}
}
}





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:tool="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="Set Date"
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:layout_marginTop="32dp"
android:fontFamily="sans-serif"
android:textSize="24sp"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="@+id/button"
tool:text="TextView" />

</androidx.constraintlayout.widget.ConstraintLayout>









How to use theme in DatePickerDialog in Android









MainActivity.java



package com.cfsuman.androidtutorials;

import android.app.DatePickerDialog;
import android.app.Dialog;
import android.os.Bundle;
import android.widget.Button;
import android.widget.DatePicker;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.view.ContextThemeWrapper;
import androidx.fragment.app.DialogFragment;
import java.util.Calendar;


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


// Show the date picker dialog
button.setOnClickListener(v -> {
// Initialize a new date picker dialog fragment
DialogFragment dialogFragment = new DatePickerFragment();

// Show the date picker dialog fragment
dialogFragment.show(
getSupportFragmentManager(),
"Date Picker"
);
});
}



public static class DatePickerFragment extends DialogFragment
implements DatePickerDialog.OnDateSetListener{

@NonNull
@Override
public Dialog onCreateDialog(Bundle savedInstanceState){
final Calendar calendar = Calendar.getInstance();
int year = calendar.get(Calendar.YEAR);
int month = calendar.get(Calendar.MONTH);
int day = calendar.get(Calendar.DAY_OF_MONTH);


// Create a ContextThemeWrapper instance
ContextThemeWrapper contextThemeWrapper
= new ContextThemeWrapper(
getActivity(),
android.R.style.Theme_Holo_Light_Dialog
//android.R.style.Theme_Holo_Dialog
);


// Return the DatePickerDialog
return new DatePickerDialog(
getActivity(),
contextThemeWrapper.getThemeResId(),
this,year,month,day
);
}


public void onDateSet(
DatePicker view, int year, int month, int day){
// Do something with the chosen date
}
}
}






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="Show DatePickerDialog"
android:textAllCaps="false"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />

</androidx.constraintlayout.widget.ConstraintLayout>









How to format DatePickerDialog selected date in Android









MainActivity.java



package com.cfsuman.androidtutorials;

import android.app.DatePickerDialog;
import android.app.Dialog;
import android.os.Bundle;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.TextView;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.fragment.app.DialogFragment;
import java.text.DateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.Locale;


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


// Show the date picker dialog
button.setOnClickListener(v -> {
// Initialize a new date picker dialog fragment
DialogFragment dFragment = new DatePickerFragment();

// Show the date picker dialog fragment
dFragment.show(
getSupportFragmentManager(),
"Date Picker"
);
});
}



public static class DatePickerFragment extends DialogFragment
implements DatePickerDialog.OnDateSetListener{

@NonNull
@Override
public Dialog onCreateDialog(Bundle savedInstanceState){
final Calendar calendar = Calendar.getInstance();
int year = calendar.get(Calendar.YEAR);
int month = calendar.get(Calendar.MONTH);
int day = calendar.get(Calendar.DAY_OF_MONTH);

return new DatePickerDialog(
getActivity(),0, this,year,month,day);
}


public void onDateSet(
DatePicker view, int year, int month, int day){

// Get the text view from XML layout
TextView textView = (TextView) requireActivity()
.findViewById(R.id.textView);


// Show the chosen date
// Because month index start from zero
int actualMonth = month+1;
// Display the unformatted date to TextView
textView.setText(
"Year : " + year + ", Month : " + actualMonth
+ ", Day : " + day + "\n\n");


// Create a Date variable/object with user chosen date
Calendar cal = Calendar.getInstance();
cal.setTimeInMillis(0);
cal.set(year, month, day, 0, 0, 0);
Date chosenDate = cal.getTime();


// Format the date using style medium and US locale
DateFormat df_medium_us = DateFormat.getDateInstance(
DateFormat.MEDIUM, Locale.US);
String df_medium_us_str = df_medium_us.format(chosenDate);
// Display the formatted date
textView.append(df_medium_us_str
+ "\nDateFormat MEDIUM, Locale US\n\n");


// Format the date using style medium and UK locale
DateFormat df_medium_uk = DateFormat.getDateInstance(
DateFormat.MEDIUM, Locale.UK);
String df_medium_uk_str = df_medium_uk.format(chosenDate);
// Display the formatted date
textView.append(df_medium_uk_str
+ "\nDateFormat MEDIUM, Locale UK\n\n");


// Format the date using style short
DateFormat df_short = DateFormat
.getDateInstance(DateFormat.SHORT);
String df_short_str = df_short.format(chosenDate);
// Display the formatted date
textView.append(df_short_str + " \nDateFormat SHORT\n\n");


// Format the date using style long
DateFormat df_long = DateFormat
.getDateInstance(DateFormat.LONG);
String df_long_str = df_long.format(chosenDate);
// Display the formatted date
textView.append(df_long_str + " \nDateFormat LONG\n\n");



// Format the date using style full
DateFormat df_full = DateFormat
.getDateInstance(DateFormat.FULL);
String df_full_str = df_full.format(chosenDate);
// Display the formatted date
textView.append(df_full_str + " \nDateFormat FULL");
}
}
}





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:tool="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="Set Date"
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:layout_marginTop="24dp"
android:fontFamily="sans-serif"
android:textSize="24sp"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="@+id/button"
tool:text="TextView" />

</androidx.constraintlayout.widget.ConstraintLayout>








How to get AM PM value from TimePickerDialog in Android









MainActivity.java



package com.cfsuman.androidtutorials;

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


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 = (Button) findViewById(R.id.button);

button.setOnClickListener(v -> {
// Initialize a new time picker dialog fragment
DialogFragment dialogFragment
= new TimePickerFragment();

// Show the time picker dialog fragment
dialogFragment.show(
getSupportFragmentManager(),
"Time Picker"
);
});
}
}





TimePickerFragment.java



package com.cfsuman.androidtutorials;

import android.app.Dialog;
import android.app.TimePickerDialog;
import android.os.Bundle;
import android.widget.TextView;
import android.widget.TimePicker;
import androidx.annotation.NonNull;
import androidx.fragment.app.DialogFragment;
import java.util.Calendar;


public class TimePickerFragment extends DialogFragment
implements TimePickerDialog.OnTimeSetListener{

@NonNull
@Override
public Dialog onCreateDialog(Bundle savedInstanceState){
// Get a Calendar instance
Calendar calendar = Calendar.getInstance();
// Get the current hour and minute
int hour = calendar.get(Calendar.HOUR_OF_DAY);
int minute = calendar.get(Calendar.MINUTE);

// Return the TimePickerDialog
return new TimePickerDialog(
getActivity(),0,
this,hour,minute,false);
}



public void onTimeSet(TimePicker view,
int hourOfDay, int minute){
// Variable to hold the current time AM PM Status
// Initially we set the variable value to AM
String status = "AM";

if(hourOfDay > 11){
// If the hour is greater than or equal to 12
// Then the current AM PM status is PM
status = "PM";
}

// Initialize a new variable to
// hold 12 hour format hour value
int hour_of_12_hour_format;


if(hourOfDay > 11){
// If the hour is greater than or equal to 12
// Then we subtract 12 from the hour
// to make it 12 hour format time
hour_of_12_hour_format = hourOfDay - 12;
}
else { hour_of_12_hour_format = hourOfDay; }


// Get the calling activity TextView reference
TextView tv = (TextView) requireActivity()
.findViewById(R.id.textView);


// Display the 12 hour format time in app interface
tv.setText(hour_of_12_hour_format
+ " : " + minute + " : " + status);
}
}





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:tool="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="Set Time"
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:layout_marginTop="24dp"
android:fontFamily="sans-serif"
android:textSize="24sp"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="@+id/button"
tool:text="TextView" />

</androidx.constraintlayout.widget.ConstraintLayout>