How to display list of items with RecyclerView in Android.

When it's come to display list of items in android the best and ease way is to use RecyclerView.
RecyclerView is android widget which uses ViewHolder patter to save the inflated views,so that when user scroll the list then views are recycle and not created again.
Recycling of views is very use full from memory and performance perspective.


So,In this tutorial,
We gone a build simple example,we create MyRecyclerViewAdapter which extends from RecyclerView.Adapter class,this class is the adapter class which hold the data and view which we display in RecyclerView.
We need layout which represent list item,which we create in word_list_item.xml file.
We Also create activity_main.xml and MainActivity.Java to display Item List.

TrendyProgrammer's Code is well commented so you can find out what is going on in code,by just Reading it.

So Let's Look the Code:

MyRecyclerViewAdapter.Java
package com.example.trendyprogrammer.recylerviewdemo;
import android.content.Context;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import java.util.LinkedList;
import static com.example.android.recyclerview.R.string.clickedText;
/**
* MyRecylerViewAdapter class , shows how to implement a simple Adapter for RecyclerView.
* And also shows how to implement click event handler for each item in th viewHolder
*/
public class MyRecyclerViewAdapter
extends RecyclerView.Adapter<MyRecyclerViewAdapter.MyViewHolder> {
private final LinkedList<String> listOfWord;
private final LayoutInflater inflater;
public MyViewHolder extends RecyclerView.ViewHolder
implements View.OnClickListener
{
public final TextView wordItemView;
final MyViewHolder adapter;
/**
* Let's create the custome view holder to hold the view
* which display in RecyclerView
*
* @param itemView The view in which we display the data.
* @param adapter the adapter object which manages view and
* data for the RecyclerView
*
*/
public MyViewHolder(View itemView, MyRecyclerViewAdapter adapter) {
super(itemView);
wordItemView = (TextView) itemView.findViewById(R.id.textViewWord);
this.adapter = adapter;
itemView.setOnClickListener(this);
}
@Override
public void onClick (View v){
//Let's change the textView when user click the RecyclerView item.
String text = v.getContext().getString(clickedText)
wordItemView.setText(text);
}
}
public WordListAdapter(Context context, LinkedList<String> wordList) {
inflater = LayoutInflater.from(context);
this.listOfWord = wordList;
}
/**
* Inflates an item view and returns a new view holder that contains it.
* Called when the RecyclerView needs a new view holder to represent an item.
*
* @param parent The view group that holds the item views.
* @param viewType Used to distinguish views, if more than one
* type of item view is used.
* @return a view holder.
*/
@Override
public MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
// Inflate an item view.
View itemView = mInflater.inflate(R.layout.word_list_item, parent, false);
return new MyViewHolder(itemView, this);
}
/**
* Let's inflate the new View and create new View Holder that contain it.
* this method called when Recycler View need new View Holder to represent
* new item
*
* @param parant The view group perent that holds the item views.
* @param position the position of the item start with 0 in the RecyclerView.
*/
@Override
public void onBindViewHolder(MyViewHolder holder, int postion) {
//Let's get the data from list .
String currentObj = listOfWord.get(position);
// Let' add the data to the view Holder.
holder.wordItemView.setText(currentObj);
}
/*
* Return the size of the list of items
*
* @return size list size
*/
@Override
public int getItemCount() {
return listOfWord.size();
}
}
word_list_item.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical"
android:padding="4dp">
<TextView
android:id="@+id/textViewWord"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:textSize="24sp"
android:textStyle="bold"/>
</LinearLayout>
MainActivity.Java
package com.example.trendyprogrammer.recylerviewdemo;
import android.os.Bundle;
import android.support.design.widget.FloatingActionButton;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import java.util.LinkedList;
/**
* MainActivity class, Implements RecyclerView that display a list of words.
* - When you click the item we mark the item as clicked.
* - When you click the fab button we add new word to the list of word.
*/
public class MainActivity extends AppCompatActivity{
private final LinkedList<String> wordList = new LinkedList<>();
private RecyclerView recyclerView;
private MyRecyclerViewAdapter myRecyclerViewAdapter;
@Override
public void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//put initial item data into the word list.
for(int i = 0 ; i < 20 ; i++){
wordList.addLast("Word" + i);
}
// Create the RecyclerView
recyclerView = (RecyclerView) findViewById(R.id.recyclerView);
// Let's create the adapter object and supply the data to be displayed.
myRecyclerViewAdapter = new MyRecyclerViewAdapter(this,wordList);
// Connect the adapte with the recyclerView.
recyclerView.setAdapter(myRecyclerViewAdapter);
//Let's set the recyclerView default layout manager
recyclerView.setLayoutManager(new LinearLayoutManager(this));
//Let's create the floating action button click handler for adding new
//list item.
FloatingActionButton fab = (FloatingActionbutton)
findViewById(R.id.button_fab);
fab.setOnClickListener(new View.OnClickListener(){
int listWordSize = wordList.size();
// Let's add new word to the wordList.
wordList.addLast("Word"+ listWordSize));
//Notify the adapter that new data is inserted.
recyclerView.getAdapter().notifyItemInserted(listWordSize);
//Let's scroll to the buttom.
recyclerView.smoothScrollToPosition(listWordSize);
});
}
}
   activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<android.support.design.widget.CoordinatorLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<android.support.v7.widget.RecyclerView
android:id="@+id/recyclerview"
android:layout_width="match_parent"
android:layout_height="match_parent">
</android.support.v7.widget.RecyclerView>
<android.support.design.widget.FloatingActionButton
android:id="@+id/button_fab"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="bottom|end"
android:layout_margin="14dp"
android:clickable="true"
android:src="@drawable/ic_icon" />
</android.support.design.widget.CoordinatorLayout>
Please Leave your Comments and Let Us Know Your Thoughts About This Tutorial. 

How to communicate between Android Activity and Fragment

In this fragment communication tutorial, We learn how to do communication between Android Activity and Fragment.
In this tutorial we create one fragment MyFragment which extends Fragment , in this fragment we create on Interface named FragmentInteractionListener this interface contain one method onRadioButtonSelected() , this method delegate choice made by user in Fragment to Activity.
Our MainActivity implements FragmentInteractionListener show when user make choice, we can get user choice in MainActivity.
In MainActivity we save user's choice and when you reopen fragment again then we can set user
previous choice.


Let's show the Code.


MainActivity.java
package com.example.tredyprogrammer.fragmentCommunication;
import android.os.Bundle;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;
import static android.widget.Toast.LENGTH_SHORT;
public class MainActivity extends AppCompatActivity
implements MyFragment.FragmentInteractionListener {
private Button button;
private boolean isFragmentShow = false;
//key for saved instance state
static final String FRAGMENT_STATE = "fragment_state";
static final String CHOICE_STATE = "user_choice";
//The radio button default choice is 2 (means no choice).
// Let's initialize the radio button choice to the default.
private int radioButtonChoice = 2;
@Override
protected void onCreate(Bundle savedInstaceState) {
super.onCreate(savedInstaceState);
setContentView(R.layout.actvity_main);
//Let's get the button for opening and closing the fragment.
button = findViewById(R.id.button_open);
//if activity returning from a configuration change,then get the
//fragment state and set the button text "open" or "close".
if (savedInstaceState != null) {
isFragmentShow = savedInstaceState.getBoolean(FRAGMENT_STATE);
radioButtonChoice = savedInstaceState.getInt(CHOICE_STATE);
if (isFragmentShow) {
//now if the fragment is displayed , change button text to "close";
button.setText("close");
}
}
//Let's set the click listener for button.
button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
if (!isFragmentShow) {
showFragment();
} else {
closeFragment();
}
}
});
}
/**
* showFragment() method call when
* user click the button to open fragment.
*/
public void showFragment() {
//create the object of MyFragment class;
MyFragment myFragment = MyFragment.newInstance(radioButtonChoice);
//get the fragmentManager and start a fragment transaction.
FragmentManager fragmentManager = getSupportFragmentManager();
FragmentTransaction fragmentTransaction = fragmentManager
.beginTransaction();
//Add the MyFragment.
fragmentTransaction.add(R.id.container, myFragment)
.addToBackStack(null).commit();
//change the button text
button.setText("close");
//set boolean flag to true,for indicate fragment is open.
showFragment = true;
}
/**
* closeMethod() called when the user clicks the button to
* close the fragment.
*/
public void closeFragment() {
//Get the fragmentManager
FragmentManager fragmentManager = getSupportFragmentManager();
//Let's check wether fragment is already showing.
MyFragment myFragment = (MyFragment) fragmentManager
.findViewById(R.id.container);
if (myFragment != null) {
//Let's create and commit the transaction to remove the fragment.
FragmentTransaction fragmentTransaction
= fragmentManager.beginTransaction();
fragmentTransaction.remove(myFragment).commit();
}
//Update the button text to "open"
button.setText("open");
//set the boolean flat to false , to indicate fragment is closed.
showFragment = false;
}
/**
* This is the FragmentInteractionListener interface
* method this method pass the user choice from fragment
* to activity and show the toast to display user choice.
*
* @param userChoice The user's radio button choice.
*/
@Override
public void onRadioButtonSelected(int userChoice) {
//save the radio button choice,to pass it back to fragment.
radioButtonChoice = userChoice
//show the toast message with radio button choice.
Toast.makeText(this, "You Choice is" + Integer.toString(userChoice), LENGTH_SHORT).show();
}
@Override
public void onSaveInstanceState(Bundle savedInstaceState) {
//Let's save the current state of fragment (true = open,false = close).
savedInstaceState.putBoolean(FRAGMENT_STATE, showFragment);
savedInstaceState.putInt(CHOICE_STATE, radioButtonChoice);
super.onSaveInstanceState(savedInstaceState);
}
}
activity_main.xml
<?xml version = "1.0" encoding="utf-8"?>
<android.support.constraint.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"
tools:context="com.example.tredyprogrammer.fragmentCommunication.MainActivity">
<TextView
android:id="@+id/title"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_marginEnd="5dp"
android:layout_marginLeft="5dp"
android:layout_marginRight="5dp"
android:layout_marginStart="5dp"
android:text="Trendy Programmer"
android:textAppearance="@style/Base.TextAppearance.AppCompat.Medium"
app:layout_constraintHorizontal_bias="0.0"
app:layout_constraintStart_toStartOf = "parent"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintTop_toTopOf="parent"/>
<FrameLayout
android:id="@+id/container"
android:name="MyFragment"
android:layout_width="0dp"
android:layout_height="0dp"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintTop_toBottomOf="@id/title"
app:layout_constraintBottom_toTopOf="@id/button_open"
tools:layout="@layout/fragment_layout" />
<Button
android:id="@+id/button_open"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="5dp"
android:layout_marginStart="5dp"
android:layout_marginTop="5dp"
android:text="open"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintBottom_ToBottomOf="parent"
/>
</android.support.constraint.ConstraintLayout>
MyFragment.java.
package com.example.tredyprogrammer.fragmentCommunication;
import android.content.Context;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.RadioGroup;
import android.widget.TextView;
/**
* Simple subclass of Fragment,which show the Question with
* radio button choises for provide feedback,if user select "Yes"
* radio button then header text will be change to "Liked".
* And if the user selected the "No" radio button then header
* text change to "Thank you".
* the user choise will save in memory so that,when
* User open fragment again we can show previous selected choice.
*/
public class MyFragment extends Fragment {
//The radios button have three different choices.
// 0 = Yes , 1 = No And 2 = default (No choice)
public static final int YES = 1;
public static final int NO = 0;
public static final int NONE_SELECTION = 2;
// Lets initialize the choise to default (NONE)
private int radioButtonChoice = NONE;
// Let's have choise key for bundle
private static final String USER_CHOICE = "choice";
//The Listener interface for activity communication.
pravate FragmentInteractionListener
fragmentInterationListener;
public MyFragment() {
// empty public constractor
}
public interface FragmentInteractionListener {
public onRadioButtonSelected(int selectedChoice);
}
/**
* onAttach() in this callback method
* we check hosting activity has implemented
* FragmentInteractionListener interface. if hosting
* activity not implemented FragmentInteractionListener
* then we throw the exception
*/
@Override
public void onAttach(Context context) {
super.onAttech(context);
if (context instanceOf FragmentInteractionListener){
this.fragmentInterationListener = (FragmentInteractionListener) context;
}else{
throw new ClassCastException(context.toString() + "Hosting actvity does not implemented
FragmentInteractionListener interface ");
}
}
/**
* Let's create the fragment view by inflating the layout, and if the
* User's previously selected choice is found then get the choice argument
* from bundle and check the radio button accourdingly "Yes or No"
* We will use RadioGroup Listener,to get the radio button selection from user.
*
* @param inflater LayoutInflater,we will use this layout inflater to inflate view.
* @param container ViewGrop of parent view in which fragment is attach.
* @param savedInstanceState Bundle for previour state
* @return rootView
*/
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container
, Bundle savedInstanceState) {
// Let's inflate the layout for fragment
final View mainView = inflater.inflate(R.layout.fragment_layout, container, false);
final RadioGroup radioGroupOfChoice = mainView.findViewById(R.id.radio_button_group);
// if user already made a choice then the bundle
// contains "choice".
if (getArguments().countainsKey(USER_CHOICE)) {
//user had a choice,so get the choice.
radioButtonChoice = getArgument().getInt(USER_CHOICE);
//Let's check the selected radio button.
if (radioButtonChoice != NONE_SELECTION) {
radioGroupOfChoice.check(radioGroupOfChoice.getChildAt(radioButtonChoice).getId());
}
}
//Let's set the onCheckedChanged listener on radioGroup
radioGroupOfChoice.setOnCheckedChangeListener(
new RadioGroup.OnCheckedChangeListener() {
@Override
public void onCheckedChanged(RadioGroup group, int checkedId) {
View checkedRadioButton = radioGroup.findViewById(checkedId);
int indexOfRadioButton = radioGroup.indexOfChild(checkeRadioButton)
TextView headerTextView =
mainView.findViewById(R.id.fragment_header_text);
switch (indexOfRadioButton) {
case YES: // User choice "Yes"
headerTextView.setText("Liked");
radioButtonChoice = YES;
fragmentInterationListener.onRadioButtonSelected(YES);
break
case NO: // User choice "No"
headerTextView.setText("Thank you");
radioButtonChoice = NO;
fragmentInterationListener.onRadioButtonSelected(NO);
break
case default: // User choice "Yes"
radioButtonChoice = NONE;
fragmentInterationListener.onRadioButtonSelected(NONE);
break
}
}
});
returm mainView;
}
public static MyFragment newInstance(int previousChoice) {
MyFragment myFragment = new MyFragment();
Bundle argument = new Bundle();
argument.putInt(USER_CHOICE, previousChoice);
myFragment.setArguments(arguments);
return fragment;
}
}
view raw MyFragment.java hosted with ❤ by GitHub
fragment_layout.xml
<?xml version="1.0" encoding = "utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#fff"
android:orientation="horizontal"
tools:context="com.example.tredyprogrammer.fragmentCommunication.MyFragment">
<TextView
android:id="@+id/fragment_header_text"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:padding="5dp"
android:text="Do you like Trendy Programmer Blog?"
android:textAppearance="@style/Base.TextAppearance.AppCompat.Medium"/>
<RadioGroup
android:id="@+id/radio_button_group"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="horizontal">
<RadioButton
android:id="@+id/radioButtonYes"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginRight="dp"
android:text="Yes"/>
<RadioButton
android:id="@+id/radioButtonNes"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginRight="5dp"
android:text="No"/>
</RadioGroup>
</LinearLayout>

Leave you comments And Let us know you thoughts about this tutorial.
-Trendy Programmer

How to Install WordPress in local computer

WordPress is CMS (content management system). Now day more than 80% website are running with WordPress.
WordPress is very easy to learn you can learn WordPress in couple of days.
We can create fully function website with WordPress withing 1 day.
In this tutorial we learn how to install WordPress in our local computer.

Step - 1
First download the latest version of WordPress from https://wordpress.org/download/
web site.


Step - 2 
Extract the downloaded .zip file and put extracted folder under the htdocs/ folder.
htdocs folder is created where you installed xampp server.(Mainly in your computer's c drive)

  
Step - 3
Now first start xampp server and go to any web browser and type localhost/demo
Note : don't forgot to replace demo folder name with your folder name where you putted extracted WordPress folder. 
Choose your desired language and press the Let's go button.


Step - 4
Now open the phpMyAdmin and create new DataBase.
Note: Save the database name to some where,because it will need in next step.


Step - 5
In this step enter the Database name which we just created in step - 4.
Enter the username this username is attached with you database,on localhost 
username is root.
You no need enter the password when you install wordpress on local computer.
Database Host will be localhost.
Table Prefix enter what type of table prefix you want in your data base.



Step - 6
Press the Run the installation button.


Step - 7
Now Enter the following fields as per you choose.
and check search engine visibility checkbox to true.
Site name - you site name
Username - username
password -  you desired password.
Your Email-  your email address.
Then press the Install WordPress button.



Step - 8
If Every thing is ok then you come up with success screen.
Press the LogIn button given in Success screen.
When you Press LogIn button you will redirected to login screen. 
Enter you Username and password in login screen press the login button.

Hurrah word is installed in you local computer.

 
Now WordPress is installed Press on visit site link given on wordpress deshborad. 
you can see the default WordPress site which come with wordpress setup.


 
Please leave you comment and let us know about your thoughts.

How to create fan control dial with android custom view.

Fan control dial example, In this example we create circular UI which represent physical fan dial control.



we use Custom view which extends from View class for draw a circular fan dial control and this custom view also draw text labels and indicator for settings fan speed.

0 means fan is off.
1 means fan is law.
2 means fan is medium.
3 means fan is high. 

When user click on fan dail then we move dial indicator to next position and we also change the fan dial color from Off to On when section is 1-3 for indicating that fan is turn on.  

Step -1       
First we create attribute file under the res/value folder this file is named attrs.xml.
In this attrs.xml file we create custom attribute for our custom fan dial view. 
attrs.xml 
<?xml version="1.0" encoding="utf-8"?>
<resource>
<declare-styleable name="FanDialView">
<attr name="onFanColor" format="reference|color" />
<attr name="offFanColor" format="reference|color" />
</declare-styleable>
</resource>
view raw attrs.xml hosted with ❤ by GitHub

Step - 2
In this step we create FanControlView class which extends View class, we will put all the logic inside this class.
 
FanControlView.java

package com.example.funcontrol.trendyprogrammer
import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.util.AttributeSet;
import android.view.View;
/*
* Custome view which create multiple-postion "Fan control dial".Each click on view increase fanControl postion
* Initially we set to 4 selection (0 to 3)
*
* 0 = off, 1 = Low, 2 = Medium, 3 = High
*/
public class FanControlView extends View {
private static int SELECTION_TOTAL_COUNT = 4; // Total number of selection we have
private float viewWidth; // Custom view width
private float viewHieght; // Custom view height
private Paint textPaint; // For text in the view
private Paint fanControlPaint; // For fan control dial circle in the view
private float radius; // Radius of the fan control dial
private int activeSelection; // The active selection
//let's have String buffer for fan control dial labels and float for calculateXY result.
private final StringBuffer tempLabels = new StringBuffer(8);
private final float[] tempResult = new float[2];
//The color will be set in attributes.
private int onFanColor; // fan cotrol dial color set in the attribute
private int offFanColor; // fan control dial color set in the attribute
/**
* Single parameter constructor called when this custom view is created from
* java code.
*
* @param context The Context the view is running in,using context this view can
* access the current theme, resources, etc.
*/
public FanControlView(Context context) {
super(context)
initialize(context, null);
}
/**
* This constructor is called when a this view is build from an xml file,
* this supplying attributes that ware specified in the xml file.
*
* @param context The Context the view is running in,using context this view can
* access the current theme, resources, etc.
* @param attrs The attributes of the XML tag that is inflating the view.
*/
public FanControlView(Context context, AttributeSet attrs) {
super(context, attrs)
initialize(context, attrs);
}
/**
* This constructor is called to supply the default style(theme)
*
* @param context The Context the view is running in,using context this view can
* access the current theme, resources, etc.
* @param attrs The Context the view is running in,using context this view can
* access the current theme, resources, etc.
* @param defStyleAttr The default style attribute.
*/
public FanControlView(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs);
initialize(context, attrs);
}
/**
* Helper method to initialize variables, this method is called by constructors.
*/
private void initialize(Context context, AttributeSet attrs) {
// we create Paint styles used in drawing here.
// This is for performance optimization , Since the OnDraw() method is called
// for every single screen refresh.
//let's set default On fan color and Off fan color
onFanColor = Color.RED;
offFanColor = Color.GREEN;
// Let's get custome attribute OnFanColor and OffFanColor , if They are available.
if (attrs != null) {
TypedArray typedArray = getContext().obtainStyledAttributes(attrs,
R.styleable.FanDialView,
0, 0);
//Let's set the fan on and off colors from the attribute values.
onFanColor = typedArray.getColor(R.styleable.FanDialView_onFanColor, onFanColor)
offFanColr = typedArray.getColor(R.styleable.FanDialView_offFanColor, offFanColor)
// recyle the TypedArray when finished
typedArray.recyle();
}
textPaint = new Paint(Paint.ANTI_ALIAS_FLAG);
textPaint.setColor(Color.Black)
textPaint.setStyle(Paint.Style.FILL_AND_STROKE);
textPaint.setTextAlign(Paint.Align.CENTER);
textPaint.setTextSize(30f);
fanControlPaint = new Paint(Paint.ANTI_ALIAS_FLAG);
//Let's set the fanControlPaint color.
fanControlPaint.setColor(offFanColor);
//Current selection (Where the fan control dial inidicator is pointing).
activeSelection = 0;
// Let's set up onClick listener for this view
// when we click on this view this click handler receiver click event
// and we Rotate the between different selection states on each click.
setOnClickListener(new OnClickListener() {
@Override
public void onClick(View view) {
// Increase the selection forward to the next available choice.
activeSelection = (activeSelection + 1) % SELECTION_TOTAL_COUNT
// Let's change the fan cotrol dial color to indicate fan is on
// when selection is >= 1
if (activeSelection >= 1) {
fanControlPaint.setColor(onFanColor)
} else {
fanControlPaint.setColor(offFanColor)
}
// call invalide for redraw the view.
invalidate();
}
});
}
/**
* onSizeChanged() method called when the size of this view has changed,
* now if this view is just added to view hierarchy , it is called with the initail
* value of 0. let' we initialize drawing bounds for the custome view in this method.
*
* @param w Current width of this view
* @param h Current height of this view
* @param oldw Initial or old width of this view
* @param oldh Initial or old height of this view
*/
@Override
protected void onSizeChanged(int w, int h, int oldw, int oldh) {
// we will calculate the radius for fan control dial in this method.
width = w;
height = h;
radius = (float) (Math.min(width, height) / 2 * 0.8);
}
/**
* Draw the view content : an outer Red circle to indicate as the "fan control dial"
* and a smaller black circle to serve as the indicator.
* The postion of the indicator is based on activeSelection.
*
* @param canvas The canvas on which all view will be draw.
*/
@Override
protected void onDraw(Canvas canvas) {
//Let's draw the fan control dial
canvas.drawCircle(width / 2, height / 2, radius, fanControlPaint);
// Let's draw the text lables for fan control dial.
final float lableRadius = radius + 20;
StringBuffer labBuffer = tempLabels;
for (int i = 0; i < SELECTION_TOTAL_COUNT; i++) {
float[] xyPostionData = calculateXYForPostion(i, lableRadius);
float x = xyPostionData[0];
float y = xyPostionData[1];
labBuffer.setLength(0);
labBuffer.append(i);
canvas.drawText(labBuffer, 0, labBuffer.length(), x, y, textPaint);
}
//Let's draw the fan control indicator marker on canvas we have.
final flaot fanMarkerIndicator = radius + 35;
flaot[] xyDataForMarkerIndicator = calculateXYForPostion(activeSelection, fanMarkerIndicator);
flaot x = xyDataForMarkerIndicator[0];
flaot y = xyDataForMarkerIndicator[1];
canvas.drawCircle(x, y, 20, textPaint);
}
/**
* calculate the x and y postion for the text lable and fan indicator,
* this method take radius and position number.
* where the text lable and fan control indicator should draw.
*
* @param postion postion index zero-based.
* @param radius The redius where fan control indicator is to be drawn.
* @return this method return 2 element array, Element 0 is x-coordinate, element 1 is Y-coordinate.
*/
private float[] calculateXYForPostion(final int postion, final float radius) {
flaot[] mResult = tempResult;
Double startingAngle = Math.PI * (9 / 8d);
Double angle = startingAngle + (postion * (Math.PI / 4));
mResult[0] = (float) (redius * Math.cos(angle)) + (width / 2);
mResult[1] = (float) (redius * Math.sin(angle)) + (height / 2);
return mResult;
}
}
  
Step - 3
In 3th Step we create activity_main.xml file under the res/layout.In activity_main.xml we use the 
FanControlView Class which we created in step-2. 

activity_main.xml

<?xml version="1.0" endcoding="utf-8"?>
<android.support.constraint.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:gravity="center_horizontal"
android:orientation="vertical"
>
<AppCompactTextView
android:id="@+id/textViewLable"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:padding="16dp"
android:text="Fan controler"
android:textAppearance="@style/TextAppearance.AppCompat.Display1"
android:layout_marginLeft="8dp"
android:layout_marginStart="8dp"
android:layout_marginEnd="8dp"
android:layout_marginRight="8dp"
android:layout_marginTop="24dp"
app:layout_constraintTop_toTopof="parent"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent" />
<com.example.funcontrol.trendyprogrammer.FunControlView
android:id="@+id/funControlView"
android:layout_width="200dp"
android:layout_height="200dp"
android:layout_marginTop="8dp"
android:layout_marginRight="8dp"
android:layout_marginLeft="8dp"
android:layout_marginStart="8dp"
app:OffFunColor="#ff0000"
app:OnFunColor="#00ff00"
app:layout_constraintTop_toBottomOf="@id/textViewLable"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintLeft_toLeftOf="parent"/>
</android.support.constraint.ConstraintLayout>
Step -4
In 4th Step we create MainActivity class which extends AppCompactActivity class,
This class is our main activity we uses activity_main.xml file to draw UI.

MainActivity.java
package com.example.funcontrol.trendyprogrammer
import android.app.Activity;
import android.os.Bundle;
public class MainActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
}
Please Leave your comment and let us know your thoughts.
So we can provide more useful tutorials.

How to create EditText view with clear Text Button

Custom EditText View


How to create custom Editing text view that includes "X" button for clearing entered text.

In this tutorial we are going learn how to make custome edit text view which containt "X" clear button and how to clear all the text from edit text view when "X" clear button is click.

I am extending EditText view class in my  CustomeEditTextWithClearButton class, so that we can get all basic functionality of EditText.

For the displaying "X" clear button image we are using
                           - SetCompoundDrawablesRelativeWithInstrinsicBounds();
of EditText view,we are setting setOnTouchListener with setOnTouchListener() method and find the touch event for the "X" button drawable for RTL and LTR Language and clear text from our CustumeEditTextView.

Let's Look at the code so we can get batter idea. 

CustomeEditTextWithClearButton.java 
package com.example.trendyprogrammer.customeedittext;
import android.content.Context;
import android.graphics.drawable.Drawable;
import android.support.v4.content.res.ResourcesCompat;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.AttributeSet;
import android.view.MotionEvent;
import android.view.View;
android.support.v7.widget.AppCompatEditText;
/**
* View which is extends EditText.
* This view provides a Clear "X" button within the text field
* which,when press, clears the text from the EditText field.
*/
public class CustomeEditTextWithClearButton
extends AppCompatEditText {
private Drawable clearButtonImage;
public CustomeEditTextWithClearButton(Context context) {
super(context)
initialize();
}
public CustomeEditTextWithClearButton(Context context, AttributeSet attrs) {
super(context, attrs)
initialize();
}
public CustomeEditTextWithClearButton(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
initialize();
}
private void initialize() {
//lets initialize our Drawable variable here
clearButtonImage =
ResourcesComact.getDrawable(getResources(),
R.drawble.ic_clear_button_red_20dp, null);
// if the clear button is tapped , clear the edittext text.
setOnTouchListener(new OnTouchListener() {
@Override
public boolean onTouch(View v, MotionEvent event) {
//Lets user the getCompoundDrawables()[2] expression to check
// The drawable is on the "End" of the thext
if ((getCompoundDrawablesRelative()[2] != null)) {
float textClearButtonStart; //Use for LTR languages
float textClearButtonEnd; //Use for RTL language
boolean isTextClearButtonClicked = false;
// let's Detect the touch in RTL or LTR layout direction.
if (getLayoutDirection() == LAYOUT_DIRECTION_RTL) {
//If layout direction is RTL ,get the end of the button on the left side
textClearButtonEnd = clearButtonImage
.getIntrinsicWidth() + getPaddingStart();
//If the touch occurred before the end of the button,
// then set isTextClearButtonIsClicked = true
if (event.getX() < clearButtonEnd) {
isTextClearButtonClicked = true;
} else {
//Layout Direction is LTR.
// Get the start of the button from the right side.
textClearButtonStart = (getWidth() - getPaddingEnd()
- clearButtonImage.getIntrinsicWidth());
//If the touch event occured after the the start of the clearButtonImage,
// set isTextClearButtonClicked to true.
if (event.getX() > textClearButtonStart) {
isTextClearButtonClicked = true;
}
}
//Now lets check for actions if the button is tapped.
if (isTextClearButtonClicked) {
//let's check for ACTION_DOWN "always occurs befor ACTION_UP".
if (event.getAction() == MotionEvent.ACTION_DOWN) {
// switch to the black image of clear button.
clearButtonImage =
ResourcesCompat.getDrawable(getResources(), R, drawable.ic_clear_black_20pd, null);
showClearButton();
}
//Now Check for the ACTION_UP.
if (event.getAction() == MotionEvent.ACTION_UP) {
//Switch to the green image of clear button.
clearButtonImage =
ResourcesCompact.getDrawable(getResources(),
R.drawable.ic_clear_green_20dp, null);
//Clear the EditText and hide the clear Button.
getText().clear();
hideClearButton();
return true;
}
} else {
return false;
}
return false;
}
});
// If text changes, show or hide text "X" clear button
addTextChangedListener(new TextWatcher() {
@Override
public void beforeTextChanged(CharSequence s,
int start, int count, int after) {
//Do nothing.
}
@Override
public void onTextChanged(CharSequence s,
int start, int before, int count) {
showClearButton()
}
@Override
public void afterTextChanged(Editable s) {
//Do nothing.
}
});
}
/*
* Show the clear "X" button.
*
*/
private void showClearButton() {
//Set the drawable image (if any) to show to the left of,
above, to the right of and below text.
SetCompoundDrawablesRelativeWithInstrinsicBounds
(null, //start of text.
null, //Top of text.
clearButtonImage, //End of text.
null); //Below the text.
}
/**
* Hides the clear button.
*/
private void hideClearButton() {
SetCompoundDrawablesRelativeWithInstrinsicBounds
(null, //start of text.
null, //Top of text.
clearButtonImage, //End of text.
null); //Below the text.
}
}
How to Use  CustomeEditTextWithClearButton 

activity_main.xml
<android.support.constraint.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"
tools:context="com.example.trendyprogrammer.customeedittext.MainActivity">
<com.example.trendyprogrammer.customeedittext.CustomeEditTextWithClearButton
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:inputType="textCapSentences"
android:textAppearance="@style/Base.TextAppearance.AppCompat.Display1"
android:hint="@string/your_name"
android:layout_gravity="start"
android:textAlignment="viewStart"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintTop_toTopOf="parent"
android:id="@+id/editTextYourName"/>
</android.support.constraint.ConstraintLayout>
MainActivity.java
package com.example.trendyprogrammer.customeedittext;;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
}


How to draw on android device screen with using your finger

Canvas Drawing Example


                                                          
  
In this example we are going to learn how to draw on device screen with custom view.

i am going to use canvas and bitmap for drawing you can use this technique when ever drawing on screen take less then 16 Milli seconds,which is frame update time on android.

In this example we are going to learn how to build custom android view, how to create bitmap, how to draw on canvas and how to handle motion events.

Not talking to much about theory let's have code.

Step-1
Create the java class which extends View class, this class will contain all the login for drawing.

 public class CanvasView extends View{}


Step-2
Define following Variables and objects and initialize them in class contractor

         private Paint paint                   - Will be use for drawing , it's like paint brash.
         private Path path;                    - We will draw with path like position A to position B.
         private int drawColor              - Color for drawing on the canvas.
         private int backgroundColor   - Background color of canvas.
         private Canvas extraCanvas    - Extra canvas for drawing.
         private Bitmap extraBitmap    - Extra Bitmap on which save the path.
         private Rect frame                   - Rectangle is for screen frame.

 

Initialize paint,drawColor,path,backgroundColor Variables in class contractor.

Like This:--

       CanvasView(Context context){
            this(context,null)
       }

       CanvasView(Context context,AttributeSet attributeSet){
             super(context)

             backgroundColor = ResourcesCompact.getColor(getResources(),R.color.green,null);

             drawColor = ResourceCompact.getColor(getResources(),R.color.yellow,null);

             //this will hold the path currently we are drawing.
             path = new Path();

             //Set the paint object,with which to draw.
             paint = new Paint();
             paint.setColor(drawColor);

             //Smoothes out edges of what is draw without affecting shape.
             paint.setAntiAlias(true);

             //Dithering affects how colors with higher-pricision
             //than the device are down-sampled.
             paint.setDither(true);

             paint.setStyle(Paint.Style.STROKE); // default is FILL
             paint.setStrokeJoin(Paint.Join.ROUND); // default is METER
             paint.setStrokeCap(Paint.Cap.ROUND); // default is BUTT
             paint.setStrokeWidth(12) // default is Heirline-width (realy thin)
      } 


Step-3
Initialize bitmap,canvas and rect varible in onSizeChanged() method.

onSizeChanged() method call when ever view's size is changed, so when view infilated and view   has  valid size at that time this method also call,so we are initialize bitmap and canvas and rect object in onSizeChanged method so that we have aqurate size of canvas,bitmap and rect for frame. 
so override onSizeChanged() methods as follow.


Like This:--

     /**
        *    onSizeChange called whenver the view changes size.
        *    Since the android view start with no size, this is also called after
        *    the view has been inflated and has a valid size.
        */
        @Override
        protected void onSizeChanged(int width,int height,
                                    int oldWidth,int oldHeight){
            super.onSizeChanged(width,height,oldwidth,oldHeight);

            //let's create the bitmap, create the canvas with bitmap, fill the canvas with color.
            extraBitmap = Bitmap.createBitmap(widht,height,Bitmap.Config.ARGB_8888);

            extraCanvas = new Canvas(extraBitmap);
            extraCanvas.drawColor(backgroundColor);


            //calculate the size of the rect , which will be the frame around the picture.
            int inset = 50;


            frame = new Rect(inset,inset,width - inset,height - inset);
        }

 

Step-4
Now override the onDraw() method and draw the bitmap and rect on canvas which passed as argument in onDraw() method.

override onDraw() method as follow.

Like This:--

      @Override
        protected void onDraw(Canvas canvas){
            //Draw the bitmap that has saved path
            canvas.drawBitmap(extraBitmap,0,0,null);

            //Draw the frame around the picture with rect.
            canvas.drawRect(frame,paint);

        }

 
Step-5  
In this step we are going to create two verible x and y which are the staring point for the path.
And also we are not draw for every single pixels,for that we are using  TOUCH_TOLERANCE
variable if finger moved greater than this distance then we are drawing on canvas else nothing we have to do.
We are creating 3 method which are used in drawing, i am creating this methods so that i can isolate the drawing code from motion event listener.


Like This:--

        // Variable for the new x,y values,
        //which are the staring point for the path
        private float x, y;

        // Don not draw every sigle pixel,
        // if the finger has moved less than this distance , don not draw
        private static final float TOUCH_TOLERANCE = 4;

        // The following methods feagure out what happens for different touch event,
        // as determined by the onTouchEvent() switch statement.
        // This keeps the swith statement
        // easier to change what happens for each event.

        
       
  private void touchIsStart(float x, float y){
            path.moveTo(x,y)
            this.x = x;
            this.y = y;
        }

        private void touchIsMove(float x , float y){
            float dx = Math.abs(x - this.x);
            float dy = Math.abc(y - this.y);

            if(dx >= TOUCH_TOLERANCE || dy >= TOUCH_TOLERANCE){
                // QuadTo() method of Path class adds a quadratic bezier from the last point,
                // approaching control point (x1,y1), and ending at (x2,y2)
                path.quadTo(this.x,this.y,(x + this.x)/2,(y + this.y)/2);

                this.x = x;
                this.y = y;

                // Draw the path in our extra bitmap to save it.
                extraCanvas.drawPath(path,paint);
            }

        private void touchIsUp(){
            //Reset the path so it is not draw again.
            path.reset();
        }   


  
Step-5  
Override the onTouchEvent() Method so that we can intercept  motion event which are fired when we touch the screen(view).
intentionally i have putted the invalidate() method inside the MotionEvent.ACTION_MOVE case because we not need to call invalidate() method for all the motion event,we are call the invalidate() method when ever we draw on canvas.

Like This:--

       @Override
        public boolean onTouchEvent(MotionEvent event){
            float x = event.getX();
            float y = event.getY();

            //I am puting Invalidate() method inside the case statements because there are many
            // other type of motion events passed into this listener,
            // and we do not want to invalidate the view for all those.

            swith(event.getAction()){
                case MotionEvent.ACTION_DOWN:
                    touchIsStart(x,y);
                    //No need to call invalidate because we are not drawing anythig.
                break;

                case MotionEvent.ACTION_MOVE:
                    touchIsMove(x,y);
                    invalidate();
                break;

                case MotionEvent.ACTION_UP:
                    touchIsUp(x,y);
                break;
           
                defualt;

                    //do nothing
            }
           }


Step-6
We not need to create xml file for defining user interface. we can create CanvasView class object which we created above,and set it as content view of our activity as i do in following code.

Like This:--

/**
 *    CanvasDrawing example shows how to Build a custom view and draw on its canvas
 */
public class MainActivity extens AppCompactActivity{
   
    @Override
    protected void onCreate(Bundle savedInstanceState){
        super.onCreate(savedInstanceState);

        CanvasView canvasView;

        // No need of xml file, just one custom view created programmatically.
        canvasView = CanvasView(this);

        //Request the full screen for layout.
        canvasView.setSystemUiVisibility(SYSTEM_UI_FLAG_FULLSCREEN);
        setContentView(canvasView);
    }


Full Code of Canvas drawing example

( 1 ) app/src/main/java/com/trenyprogrammer/canvasexample/CanvasView.java

package com.trendyprogrammer.canvasexample;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.graphics.Path;
import android.graphics.Rect;
import android.support.v4.content.res.ResourcesCompat;
import android.util.AttributeSet;
import android.view.MotionEvent;
import android.view.View;
import android.content.res.Resources;

/**
 * Custom view class which follow the touch events to draw on canvas.
 */

 public class CanvasView extends View{

         private Paint paint;
         private Path path;
         private int drawColor;
         private int backgroundColor;
         private Canvas extraCanvas;
         private Bitmap extraBitmap;
         private Rect frame;

         CanvasView(Context context){
             this(context,null)
         }

         CanvasView(Context context,AttributeSet attributeSet){
             super(context)

             backgroundColor = ResourcesCompact.getColor(getResources(),R.color.green,null);

             drawColor = ResourceCompact.getColor(getResources(),R.color.yellow,null);

             //this will hold the path currently we are drawing.
             path = new Path();

             //Set the paint object,with which to draw.
             paint = new Paint();
             paint.setColor(drawColor);

             //Smoothes out edges of what is draw without affecting shape.
             paint.setAntiAlias(true);

             //Dithering affects how colors with higher-pricision
             //than the device are down-sampled.
             paint.setDither(true);

             paint.setStyle(Paint.Style.STROKE); // default is FILL
             paint.setStrokeJoin(Paint.Join.ROUND); // default is METER
             paint.setStrokeCap(Paint.Cap.ROUND); // default is BUTT
             paint.setStrokeWidth(12) // default is Heirline-width (realy thin)
         }

        /**
        *    onSizeChange called whenver the view changes size.
        *    Since the android view start with no size, this is also called after
        *    the view has been inflated and has a valid size.
        */
        @Override
        protected void onSizeChanged(int width,int height,
                                    int oldWidth,int oldHeight){
            super.onSizeChanged(width,height,oldwidth,oldHeight);

            //let's create the bitmap, create the canvas with bitmap, fill the canvas with color.
            extraBitmap = Bitmap.createBitmap(widht,height,Bitmap.Config.ARGB_8888);
            extraCanvas = new Canvas(extraBitmap);
            extraCanvas.drawColor(backgroundColor);

            //calculate the size of the rect , which will be the frame around the picture.
            int inset = 50;

            frame = new Rect(inset,inset,width - inset,height - inset);
        }

        @Override
        protected void onDraw(Canvas canvas){
            //Draw the bitmap that has saved path
            canvas.drawBitmap(extraBitmap,0,0,null);

            //Draw the frame around the picture with rect.
            canvas.drawRect(frame,paint);
        }

        // Variable for the new x,y values,
        //which are the staring point for the path
        private float x, y;

        // Don not draw every sigle pixel,
        // if the finger has moved less than this distance , don not draw
        private static final float TOUCH_TOLERANCE = 4;

        // The following methods feagure out what happens for different touch event,
        // as determined by the onTouchEvent() switch statement.
        // This keeps the swith statement
        // easier to change what happens for each event.

        private void touchIsStart(float x, float y){
            path.moveTo(x,y)
            this.x = x;
            this.y = y;
        }

        private void touchIsMove(float x , float y){
            float dx = Math.abs(x - this.x);
            float dy = Math.abc(y - this.y);

            if(dx >= TOUCH_TOLERANCE || dy >= TOUCH_TOLERANCE){
                // QuadTo() method of Path class adds a quadratic bezier from the last point,
                // approaching control point (x1,y1), and ending at (x2,y2)
                path.quadTo(this.x,this.y,(x + this.x)/2,(y + this.y)/2);

                this.x = x;
                this.y = y;

                // Draw the path in our extra bitmap to save it.
                extraCanvas.drawPath(path,paint);
            }

        private void touchIsUp(){
            //Reset the path so it is not draw again.
            path.reset();
        }   

        @Override
        public boolean onTouchEvent(MotionEvent event){
            float x = event.getX();
            float y = event.getY();

            //I am puting Invalidate() method inside the case statements because there are many
            // other type of motion events passed into this listener,
            // and we do not want to invalidate the view for all those.

            swith(event.getAction()){
                case MotionEvent.ACTION_DOWN:
                    touchIsStart(x,y);
                    //No need to call invalidate because we are not drawing anythig.
                break;

                case MotionEvent.ACTION_MOVE:
                    touchIsMove(x,y);
                    invalidate();
                break;

                case MotionEvent.ACTION_UP:
                    touchIsUp(x,y);
                break;
           
                defualt;

                    //do nothing
            }
           }

           //Get the width of the screen in pixel
           public static int getScreenWithInPixel(){
               return Resources.getSystem().getDisplayMetrics().widthPixels;
           }

           //Get the hight of the screen in pixel
           public static int getScreenHeightInPixel(){
               return Resources.getSystem().getDisplayMetrics().HeightPixels;
           }

}


( 2 ) app/scr/main/java/com/trendyprogrammer/canvasexample/MainActivity.java

package com.trendyprogrammer.canvasexample

import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import static android.view.View.SYSTEM_UI_FLAG_FULLSCREEN;

/**
*    CanvasDrawing example shows how to Build a custom view and draw on its canvas
*/
public class MainActivity extens AppCompactActivity{
   
    @Override
    protected void onCreate(Bundle savedInstanceState){
        super.onCreate(savedInstanceState);

        CanvasView canvasView;

        // No need of xml file, just one custom view created programmatically.
        canvasView = CanvasView(this);

        //Request the full screen for layout.
        canvasView.setSystemUiVisibility(SYSTEM_UI_FLAG_FULLSCREEN);
        setContentView(canvasView);
    }
}
 


Please leave your comments and let us know you opinion about this example.

you can download example code from here.






How to create android home screen widget with example


AppWidgetSample

Home widget is Representative of you application, all the home screen widget are listed in widget list and user can choose which ever widget they want to put on there home screen.

app widget provide user necessary information from your application, you can use app widget and increase user engagement with your application.

In Android development of app widget is very much easy, you can build fully function app widget with same line of code.

so, i am not going very much deep in theory, let's do same piratical.  

Pre-requesites
For this app you should be familiar with :
  1. Creating,building and ruining application in android studio.
  2. Sending and receiving broadcast intents.  
  3. Creating and sending pending intents.     

Image:-Widget list 
 Step-1
create new_app_widget_information.xml file under the app/src/main/res/xml/ directory of you project, this file contain all the meta data of the application widget which provide android os all the information necessary for app widget like app widget initial layout and app widget update cycle in milliseconds and other information


app/src/main/res/xml/new_app_widget_information.xml

<?xml version="1.0" encoding="utf-8"?>
<appwidget-provider
    xmlns:android:="https://schemas.android.com/apk/res/android"
    android:initialKeyguardLayout="@layout/new_appwidget_layout"
    android:initialLayout="@layout/new_appwidget_layout"
    android:minHeight="185dp"
    android:minWidth="120dp"
    android:previewImage="@drawable/appwidget_preview"
    android:resizeMode="horizontal|vertical"
    android:updatePeriodMillis="1800000"
    android:widgetCategory="home_screen">
</appwidget-provider> 
  
 


step - 2
Now create the layout as you wish for your app widget.
This layout will display on home screen where the user will place the widget.

app/src/main/res/layout/new_app_widget.xml

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
    xmlns:andorid="http://schemas.android.com/apk/res/android"
    xmlns:tools="https://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="#05C"
    android:padding="10dp">

    <LinearLayout>
        android:id="@+id/sectionId"
        style="@style/AppWidgetSection"
        android:layout_width="match_parent"
        android:layout_heigh="match_parent"
        android:layout_alignParentLeft="true"
        android:layout_alignParentStart="true"
        android:layout_alignParentTop="true"
        android:orientation="horizontal">


        <TextView
            android:id="@+id/appWidgetLabel"
            style="@style/AppWidgetLabel"
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_weight="2"
            android:text="@string/widgetIdLabel"
            />
        <TextView
            android:id="@+id/appWidgetId"
            style="@style/AppWidgetText"
            android:layout_width="0dp"
            android:layout_height="wrep_contect"
            android:layout_weight="1"
            android:gravity="end"
            android:text="XX"
            />
    </LinearLayout>

    <!-- Panel for widget update date and number of updates -->
    <LinearLayout
        android:id="@+id/sectionUpdate"
        style="@style/AppWidgetSeciont"
        android:layout_width="match_parent"
        android:layout_height="wrap_contect"
        android:layout_align_parentLeft="true"
        android:layout_align_parentStart="true"
        android:layout_below="@id/sectionId"
        android:orientation="vertical">

        <TextView
            android:id="@+id/appWidgetUpdateLabel"
            style="@style/AppWidgetLabel"
            android:layout_width="match_parent"
            android:layout_height="wrap_contect"
            android:layout_marginBottom="2dp"
            android:text="@string/widgetUpdateLabel"
            />
        <TextView
            android:id="@+id/appWidgetUpdate"
            style="@style/AppWidgetText"
            android:layout_width="match_parent"
            android:layout_height="wrap_contect"
            android:text="@string/dateCountFormat"/>

        </LinearLayout>

        <!-- Button for udpate widget -->
        <Button
            android:id="@+id/buttonUpdate"
            style="@style/AppWidgetButton"
            android:layout_width="wrap_contect"
            android:layout_height="wrap_contect"
            android:layout_centerHorizontal="true"
            android:text="@string/updateWidgetBottom"
            />
    </RelativeLayout>

 

 Step - 3
Create the class which will extends AppWidgetProvider class from android framework, this class will be broadcast receiver which will receive all the update send by app widget when user interact with it.
You have to create RemoteViews class object from layout which we define above and after that you need to create pending intent and bind it with any desired view click event handler.

app/src/main/java/com/example/techbuffalos/appwidgetexample/NewAppWidget.java

package com.example.techbuffalos.appwidgetsample;

import android.app.PendingIntent;
import android.appwidget.AppWidgetManager;
import android.appwidget.AppWidgetProvider;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.widget.RemoteViews;
import java.text.DateFormat;
import java.util.Date;

/*
* App widget provider class, to handle update broadcast intents and updates
* for the app widget
*/
public class NewAppWidget extends AppWidgetProvider{
   
    //Name of the shared preferances file.
    private static final String SHARE_PREF_FILE_NAME =    "com.example.techbuffalos.appwidgetsample";
    private static final String COUNT_KEY = "count";

/**
*    Update a single app widget.This is a helper method for the standard
*   onUpdate() callback that handles on widget update at a time.

*
*   @param context                 The application context.
*   @param appWidgetManager     The app widget manager.
*   @param appWidgetId          The current app widget id.
*
*/
private void updateAppWidget(Context context,
                            AppWidgetManager appWidgetManager,
                            int appWidgetId){

    // Retrive count from prefs.
    SharedPreferences prefsObj =
            context.getSharedPreferences(SHARE_PREF_FILE_NAME,0);

    int count = prefsObj.getInt(COUNT_KEY + appWidgetId,0);
    count++;

    //Get the current time
    String dateString=
        DateFormat.getTimeInstance(DateFormat.SHORT).format(new Date());

    RemoteViews view = new RemoteViews(context.getPackageName(),R.layout.new_app_widget.xml);

    views.setTextViewText(R.id.appWidgetId,String.valueOf(appWidgetId));
    views.setTextViewText(R.id.appWidgetUpdate,
            context.getResource().getString(
                R.string.data_count_format,count,dateString));   


    //save count back to prefs file
    SharedPreference.Editor prefEditor = prefObj.edit()
    prefEditor.putInt(COUNT_KEY + appWidgetId,count);
    prefEditor.apply();   

    //Setup update button to send update requrest as a pending intent
    Intent intentUpdate = new Intent(context,NewAppWidget.class);

    intentUpdate.setAction(AppWidgetManger.ACTION_APPWIDGET_UPDATE);

    // Include widget id to be update as intent extra
    int[] appWidId = new Int[]{appWidgetId};
    intentUpdate.putExtra(AppWidgetManager.EXTRA_APPWIDGET_IDS,appWidId);

    //wrap it all in intent to send a broadcast.
    //Use app widget id as request code (second argument) so that
    //each intent is unique.

    PendingIntent pendingIntent = PendingIntent.getBroadCast(context,
                appWidgetId,intentUpdate,PendingIntent.FLAG_UPDATE_CURRENT);

    //Assign pending intent to the button on click handler
    views.setOnClickPendingIntent(R.id.buttonUpdate,pendingIntent);


    //instract the app widget manager for update the widget.
    appWidgetManageer.updateAppWidget(appWidgetId,views);               
    }

    /**
    *    Override onUpdate method for handle all widget update request.
    *   
    *   @param context                 The application context.
    *   @param appWidgetManager     The app widget manager.
    *   @param appWidgetIds         An array of the app widget IDs.   
    */
    @Override
    public void onUpdate(Context context,AppWidgetManager appWidgetManager,int[] appWidgetIds){
   
        //There can be multiple widget active, so update all of them.
        for(int appWidgetId : appWidgetIds){
            updateAppWidget(context,appWidgetManager,appWidgetId)
        }
    }
}  


Step - 4 
Now one step to go, you need to register you AppWidgetProvider class to AndroidManifest.xml file as a BroadcastReceiver with android.appwidget.action.APPWIDGET_UPDATE intent action.
And also you must need to provide meta data with resource point to file which we create in step-1

app/src/main/AndoridManifest.xml

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
          package="com.example.android.appwidgetsample">

    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:supportsRtl="true"
        android:theme="@style/AppTheme">


        <activity android:name=".MainActivity">
            <intent-filter>
                <action android:name="android.intent.action.MAIN"/>
                <category android:name="android.intent.category.LAUNCHER"/>
            </intent-filter>
        </activity>

        <receiver android:name=".NewAppWidget">
            <intent-filter>
                <action android:name="android.appwidget.action.APPWIDGET_UPDATE"/>
            </intent-filter>
            <meta-data
                android:name="android.appwidget.provider"
                android:resource="@xml/new_app_widget_information"/>
        </receiver>
    </application>
</manifest>

 
Bonus : 
Here is the style.xml file which contain all the style which i used in in this example.

app/src/main/res/values/styles.xml

<?xml version="1.0" encoding="utf-8"?>
<resource>

<!-- Base application theme -->
<style name="AppTheme" parent="Theme.AppCompact.Light.DarkActionBar">
    <!-- Customize your theme here -->
    <item name="colorPrimary">@color/colorPrimary</item>
    <item name="colorPrimaryDark">@color/colorPrimartyDark</item>
    <item name="colorAccent">@color/colorAccent
</style>

<!-- style for widget's panle - linear layout with white backgournd -->
<style name="AppWidgetSection" parent="@android:style/widget">
   <item name="android:padding">8dp</item>
   <item name="android:layout_marginTop">12dp</item>
   <item name="android:layout_marginLeft">12dp</item>
   <item name="android:layout_marginRight">12dp</item>
   <item name="android:background">@android:color/white</item>
</style>

<!-- style for app widget for labels and main text -->
<style name="AppWidgetLabel" parent="AppWidgetText">
    <item name="android:textStyle">bold</item>
</style>

<!-- style for app widget button -->
<style name="AppWidgetButton" parent="Base.Widget.AppCompat.Button">
    <item name="android:layout_marginTop">12dp</item>
</style>

<style name="AppWidgetText" parent="Base.TextAppearance.AppCompat.Subhead">
    <item name="android:textColor">@android:color/black</item>
</style>
</resource>


Hope you all like this example,
Please leave you comments And let me know your thoughts about this post.

You can download all the code from here.