Custom MenuItem with Notification on it



Step 1: (build.gridle Module: app)

Add dependency
Compile ‘com.android.support:appcompact-v7:26.1.0’


Step 2: (values/styles.xml)

In styles.xml copy the current style and paste and change name of it and also change parent to NoActionBar i.e. parent="Theme.AppCompat.Light.DarkActionBar">
Note: This is important because we have to set ToolBas as our ActonBar so we should remove it by this style


<style name="noActionBar"
parent="Theme.AppCompat.Light.NoActionBar">
        <!-- Customize your theme here. -->
        <item name="colorPrimary">@color/colorPrimary</item>
        <item name="colorPrimaryDark">@color/colorPrimaryDark</item>
        <item name="colorAccent">@color/colorAccent</item>
    </style>


Step 3: (AndroidManifest.xml)

Set theme as our created style for our particular activity
<activity android:name=".YourActivity"
      android:theme="@style/noActionBar"/>
Then re-sync the Project


Step 4: (YourActivity.xml Layout)

1> Add ToolBar from AppCompact in Palette
Make sure That ToolBar is
<android.support.v7.widget.Toolbar />

Give id to it
android:id="@+id/my_toolbar"

Layout Code:

<android.support.v7.widget.Toolbar
    android:id="@+id/my_toolbar"
    android:layout_width="0dp"
    android:layout_height="wrap_content"
    android:layout_alignParentLeft="true"
    android:layout_alignParentStart="true"
    android:layout_alignParentTop="true"
    android:background="?attr/colorPrimary"
    android:fitsSystemWindows="true"
    android:minHeight="?attr/actionBarSize"
    android:theme="?attr/actionBarTheme"
    app:layout_constraintEnd_toEndOf="parent"
    app:layout_constraintStart_toStartOf="parent"
    app:layout_constraintTop_toTopOf="parent" />

2> Then Button and TextView to it
<Button
    android:id="@+id/add_to_cart_btn"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_marginBottom="209dp"
    android:background="?selectableItemBackgroundBorderless"
    android:text="+"
    android:textSize="30sp"
    app:layout_constraintBottom_toBottomOf="parent"
    app:layout_constraintEnd_toEndOf="parent"
    app:layout_constraintStart_toStartOf="parent" />

<TextView
    android:id="@+id/countTv"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_marginBottom="52dp"
    android:layout_marginEnd="36dp"
    android:text="0"
    android:textSize="30sp"
    app:layout_constraintBottom_toTopOf="@+id/add_to_cart_btn"
    app:layout_constraintEnd_toEndOf="@+id/add_to_cart_btn" />


Step 5: (drawable/rounded_textView.xml)

Then create drawable resource file named as rounded_textView.xml file add this code in it
By this we will create a shape to set it on TextView to show it as Circular TextView
<?xml version="1.0" encoding="utf-8"?>
    <shape xmlns:android="http://schemas.android.com/apk/res/android"
        android:shape="oval">

        <solid android:color="#FF5400" />
        <size
            android:height="20dp"
            android:width="20dp" />

    </shape>


Step 6: (drawable)

Download the icon for MenuItem from this site Link: https://material.io/icons/
And paste it in Drawable directory


Step 7: (Layout/cart_layout.xml)


Now create new layout resources file in layout directory
Named cart_layout
>And Add ImageButton and TextView on it
>And set Image Background as icon Downloaded and foreground as
android:foreground="?android:selectableItemBackground"
 to show animation when clicked
>And set background of textView as
android:background="@drawable/rounded_textview"

Code: (Layout/cart_layout.xml)

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout 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">

    <RelativeLayout
        android:id="@+id/relative_layout_cart_ic"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content">

        <ImageButton
            android:id="@+id/cart_ic_image"
            android:layout_width="40dp"
            android:layout_height="40dp"
            android:layout_alignParentLeft="true"
            android:layout_alignParentStart="true"
            android:layout_alignParentTop="true"
            android:layout_marginEnd="10dp"
            android:layout_marginLeft="10dp"
            android:layout_marginRight="10dp"
            android:layout_marginStart="10dp"
            android:layout_marginTop="5dp"
            android:background="@drawable/ic_shopping_cart_black_24dp"
            android:foreground="?android:selectableItemBackground" />

        <TextView
            android:id="@+id/count_tv"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_alignTop="@+id/cart_ic_image"
            android:layout_centerHorizontal="true"
            android:background="@drawable/rounded_textview"
            android:gravity="center"
            android:text="0"
            android:textColor="@android:color/white"
            android:textSize="12sp"
            tools:layout_editor_absoluteX="32dp"
            tools:layout_editor_absoluteY="7dp" />


    </RelativeLayout>

</RelativeLayout>


Step 7: (menu/menu.xml)

Now Create new Directory in res named as menu
Note: menu directory is not present we have to create new manually
And in that menu directory create new menu resources file called

Menu.xml

And inside it write the below code:
<item
    android:id="@+id/cart_count_menu_item"
    app:showAsAction="always"
    app:actionLayout="@layout/cart_layout"
    android:title="Cart">
</item>

In app:actionLayout attribute we have set our layout which we have to inflate over our MenuItem
app:actionLayout="@layout/cart_layout"


Step 8: (YourActivity.xml Layout)

> Import Library only of v7 ToolBar i.e.
import android.support.v7.widget.Toolbar;

>Now in your Activity Create new Object for TextView Button and ToolBar and join them with kayout file
>And ya we have to call
setSupportActionBar()
method and pass ToolBar object to its parameter

>And setTitleTextColor to it
myToolBar.setTitleTextColor(0xFFFFFFFF);

Toolbar myToolBar;
Button addToCartBtn;
TextView countTv;


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

    myToolBar = findViewById(R.id.my_toolbar);
    setSupportActionBar(myToolBar);

    myToolBar.setTitleTextColor(0xFFFFFFFF);

    addToCartBtn=findViewById(R.id.add_to_cart_btn);
    countTv=findViewById(R.id.countTv);
}


Step 9: (YourActivity.xml Layout)

> Now Create new onCreateOptionMenu() method and Inflate our menu.xml to ToolBar by
getMenuInflater().inflate(R.menu.menu, menu);

> Now Create Global variable for MenuItem
MenuItem cartIconMenuItem;

> And Inflate the MenuItem by Menu.findItem() method
cartIconMenuItem = menu.findItem(R.id.cart_count_menu_item);

> Now create new variable for View and call MenuItem.getActionView() method to give
ActionView to view variable
View actionView = cartIconMenuItem.getActionView();

>Now check if actionView is not null in if statement
Code Snippet:
if (actionView != null) {
   
}

>Now in if condition inflate ImageButton and TextView to global variable of it
if (actionView != null) {
    countTvMenuItem=actionView.findViewById(R.id.count_tv);
    cartImageButtonwMenuItem=actionView.findViewById(R.id.cart_ic_image);
}

Note: For setting onClick on our custom MenuItem we have to set onClick on ImageButton Inflated, in onCreateOptionMenu() method

cartImageButtonwMenuItem.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View view) {
        Intent intent = new Intent(MainActivity.this, ToolBarTest2.class);
        startActivity(intent);
    }
});
and return true or return super.onCreateOptionsMenu(menu);


Code of onCreateOptionMenu :

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    getMenuInflater().inflate(R.menu.menu, menu);


    getSupportActionBar().setDisplayHomeAsUpEnabled(true);
    getSupportActionBar().setDisplayShowHomeEnabled(true);

    cartIconMenuItem = menu.findItem(R.id.cart_count_menu_item);
    View actionView = cartIconMenuItem.getActionView();

    if (actionView != null) {
        countTvMenuItem=actionView.findViewById(R.id.count_tv);
        cartImageButtonwMenuItem=actionView.findViewById(R.id.cart_ic_image);
    }


    cartImageButtonwMenuItem.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            Intent intent = new Intent(MainActivity.this, ToolBarTest2.class);
            startActivity(intent);
        }
    });

   
    return super.onCreateOptionsMenu(menu);
}


Step 10: (YourActivity.xml Layout)

Now create new Method in your activity class called onIncrement()
>And now create global variable of int count;
>And do increment of count in this method
>And set the Incremented number to TextView of ActionView and Activity TextView

Code doIncrease() Method: 

private void doIncrease() {
        mCount++;
        countTv.setText(String.valueOf(mCount));
        countTvMenuItem.setText(""+mCount);
    }



Step 11: (YourActivity.xml Layout)

>Now call onDecrement() method in onClick of our Activity Button in onCreate

addToCartBtn.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View view) {
        doIncrease();
    }
});

----Done----

MainActivity.java (Activity Java File)

import android.content.Context;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.Toolbar;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.TextView;
import android.widget.Toast;

public class MainActivity extends AppCompatActivity {

    Toolbar mMyTollbar;
    Button mPlusBtn;
    ImageButton mImageBtn;
    TextView mActivityTv, mCountTv;
    MenuItem mCartIconMenuItem;
    int mCount = 0;
    Context mContext = MainActivity.this;

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

        mMyTollbar = findViewById(R.id.myToolBar);
        setSupportActionBar(mMyTollbar);
        mMyTollbar.setTitleTextColor(0xFFFFFFFF);

        mPlusBtn = findViewById(R.id.plus_btn);
        mActivityTv = findViewById(R.id.activity_tv);

        mPlusBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                doIncrement();
            }
        });
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {

        getMenuInflater().inflate(R.menu.menu, menu);
        mCartIconMenuItem = menu.findItem(R.id.cart_count_menu_item);

        View actionView = mCartIconMenuItem.getActionView();

        if (actionView != null) {
            mCountTv = actionView.findViewById(R.id.count_tv_layout);
            mImageBtn = actionView.findViewById(R.id.image_btn_layout);
        }

        mImageBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Toast.makeText(mContext, "Image Button is Clicked!", Toast.LENGTH_LONG).show();
            }
        });

        return super.onCreateOptionsMenu(menu);
    }

    private void doIncrement() {
        mCount++;
        mCountTv.setText(String.valueOf(mCount));
        mActivityTv.setText(String.valueOf(mCount));
    }
}

activity_main.xml (Activity layout)

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout 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.support.v7.widget.Toolbar
        android:id="@+id/myToolBar"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_alignParentLeft="true"
        android:layout_alignParentStart="true"
        android:layout_alignParentTop="true"
        android:background="?attr/colorPrimary"
        android:minHeight="?attr/actionBarSize"
        android:theme="?attr/actionBarTheme"
        tools:layout_editor_absoluteX="0dp"
        tools:layout_editor_absoluteY="0dp" />
    <Button
        android:id="@+id/plus_btn"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentBottom="true"
        android:layout_centerHorizontal="true"
        android:layout_marginBottom="155dp"
        android:background="?attr/selectableItemBackgroundBorderless"
        android:text="+"
        android:textSize="30sp" />
    <TextView
        android:id="@+id/activity_tv"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerHorizontal="true"
        android:layout_centerVertical="true"
        android:text="0"
        android:textSize="30sp" />

</RelativeLayout>

res/menu/menu.xml (menu Directories menu resources file)

<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto">
    <item
        android:id="@+id/cart_count_menu_item"
        android:title="Cart"
        app:actionLayout="@layout/cart_layout"
        app:showAsAction="always"></item>
</menu>

layouts/cart_layout.xml (Layout resources file for Inflating Cart MenuItem Layout)

<?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">
    <RelativeLayout
        android:layout_width="wrap_content"
        android:layout_height="wrap_content">
        <ImageButton
            android:id="@+id/image_btn_layout"
            android:layout_width="40dp"
            android:layout_height="40dp"
            android:layout_margin="10dp"
            android:background="@drawable/ic_shopping_cart_black_24dp"
            android:foreground="?attr/selectableItemBackgroundBorderless"
            tools:layout_editor_absoluteX="7dp"
            tools:layout_editor_absoluteY="16dp" />
        <TextView
            android:id="@+id/count_tv_layout"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_alignParentTop="true"
            android:layout_centerHorizontal="true"
            android:layout_marginTop="11dp"
            android:background="@drawable/rounded_textview"
            android:gravity="center"
            android:text="0"
            android:textColor="@android:color/background_light"
            android:textSize="12sp" />
    </RelativeLayout>
</android.support.constraint.ConstraintLayout>

res/drawable/rounded_textview.xml (drawable resources file for textView background shape)

<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"
    android:shape="oval">

    <solid android:color="#FF5400"/>
    <size
        android:width="20dp"
        android:height="20dp"/>
</shape>

res/values/styles.xml (values default style.xml file code)

<resources>

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

Comments

Popular posts from this blog

Java Project of restaurant dish menu System with File handling java IO | With Code

Encoded Password Save in database | asp.net with c#