Chip icon – Round chip icon using picasso library android

Chip icon using picasso library

Chip (s) are compact elements that represent an attribute, text, entity, or action. They allow users to enter information, select a choice, filter content, or trigger an action.

Chip manages its own start (app:chipIcon) and end (app:closeIcon) drawables. Picasso allows for hassle-free image loading . Normal case picasso load images and that image is converted to drawable for Icon. Which works only if image is already cached. Otherwise the resulting icon is placeholder image or error image.By using trigger a callback is created which will get the image and place it.It only works by using setTag, With out “setTag” trigger get garbage collected.

BottomApp Bar Material Theme 2

ChipGroup

A ChipGroup is used to hold multiple Chips. By default, the chips are reflowed across multiple lines. Set the app:singleLine attribute to constrain the chips to a single horizontal line. If you do so, you’ll usually want to wrap this ChipGroup in a HorizontalScrollView.

ChipGroup also supports a multiple-exclusion scope for a set of chips. When you set the app:singleSelection attribute, checking one chip that belongs to a chip-group unchecks any previously checked chip within the same group. The behavior mirrors that of RadioGroup.

MainActivity

public class MainActivity extends AppCompatActivity {

    private LinkedHashMap<String, Target> chipRecordHash;
    private ChipGroup chipGroup;
    private String [] nameList={"Google","Android","Windows","Chrome","Git hub","Facebook"};
    private String [] iconList={"https://cdn2.iconfinder.com/data/icons/social-icons-33/128/Google-512.png",
            "https://cdn2.iconfinder.com/data/icons/social-icons-33/128/Android-512.png",
            "https://cdn1.iconfinder.com/data/icons/logotypes/32/windows-512.png",
            "https://cdn1.iconfinder.com/data/icons/smallicons-logotypes/32/chrome-512.png",
            "https://cdn0.iconfinder.com/data/icons/octicons/1024/mark-github-512.png",
            "https://cdn1.iconfinder.com/data/icons/logotypes/32/square-facebook-512.png"};

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        Toolbar toolbar = findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);
        chipGroup=findViewById(R.id.chipGroup);

        intChips();

        MaterialButton remove=findViewById(R.id.remove);
        remove.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                removeChip("Facebook");
            }
        });


    }

    private void intChips(){
        chipRecordHash=new LinkedHashMap<>();
        for (int i=0;i<nameList.length;i++) {
            final Chip chip = new Chip(this, null, R.style.Widget_MaterialComponents_Chip_Action);
            chip.setText(nameList[i]);
            chip.setCloseIconVisible(true);
            chipGroup.addView(chip);
            final int finalI = i;
            chip.setOnCloseIconClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    chipGroup.removeView(chip);
                    chipRecordHash.remove(nameList[finalI]);
                }
            });
            Target target=getTargetOfPicasso(chip);
            String linkOfIcon=iconList[i];
            Picasso.get().load(linkOfIcon).error(R.drawable.icon_no_image).
                    placeholder(R.drawable.icon_place_holder).
                    transform(new CircleTransform()).resize(30,30).into(target);

            chip.setTag(target);
            // --- setting target as tag is in-case the images is not loaded the target get garbage collected
            // setTaging the target prevent it from garbage collecting

            chipRecordHash.put(nameList[i],target);
            //If you want to remove some chips threw another ways like button click etc
        }
    }


    private Target getTargetOfPicasso(final Chip targetChip){
        return new Target() {
            @Override
            public void onBitmapLoaded(Bitmap bitmap, Picasso.LoadedFrom from) {
                Drawable d = new BitmapDrawable(getResources(), bitmap);
                targetChip.setChipIcon(d);
            }
            @Override
            public void onBitmapFailed(Exception e, Drawable errorDrawable) {
                targetChip.setChipIcon(errorDrawable);
            }
            @Override
            public void onPrepareLoad(Drawable placeHolderDrawable) {
                targetChip.setChipIcon(placeHolderDrawable);
            }
        };
    }

    private void removeChip(String chipName){
        Chip chip=chipGroup.findViewWithTag(chipRecordHash.get(chipName));

        if (chip!=null) {
            chipGroup.removeView(chip);
            chipRecordHash.remove(chipName);
        }else {
            Toast.makeText(this,"Not available",Toast.LENGTH_SHORT).show();
        }

    }

}

Xml For MainActivity




        
                

                

                
        


Bottom App Bar – New Material theme 2

Bottom App Bar is introduced in material theme-2( check usage in material.io). The main advantage of bottom bar is it’s positioning bottom of the screen.You can use it with the default drawer-layout or with bottom sheet(You can check here). Both work flawlessly with bottom bar. In order to make the look and feel great of the app we are using bottom sheet.

Adding Bottom App Bar

First step is to add the Bottom App Bar to the layout in order to use this App Bar. The project must be converted to AndroidX (Option for this is available in Refactor menu in Android Studio. Add below code to your xml.

   

    

You can check out the source code

Adding option menu to bottom bar

Normally added option menus are not visible on the bottom bar, You need to set it by making the bottom bar as the default toolbar.Below code will help you achieve that.

    BottomAppBar bar=findViewById(R.id.bar);
    setSupportActionBar(bar);

Styling bottom bar and bottom sheet

For achieving the desired look Both the bottom bar and bottom sheet need styling.So style file require few more lines of code.

 

    

    

Bottom Sheet implementation for Android – Logicchip

Itext 5 – creating custom PDF in android

Creating custom PDF using iText, iText Software is a global specialist in PDF. As a PDF library, it can be embedded into document solution workflows in industries such as; Legal, Finance, Governance, IT, Operations and more.We are using iText 5 here you can check there examples here.

The output is something like the image shown below.

pdf created using itext

Adding iText dependency

First add dependencies for iText5, We are using Material design 2 here .

dependencies {     implementation'com.itextpdf:itextg:5.5.10' } 

Main Activity

Conversion from array-list to PDF document took place in MainActivity. The array-list are provided by Const.java class Footer is created using HeaderFooter.java class. First we need to provide the location of the file in order to save it, run-time permission is required for accessing the storage of the device. This example shows a list of objects and the goal is to make PDF out of that list. We used table ( PdfPTable ) to arrange the contents to ensure the correct look and feel there are lot of other objects available for arranging contents to choose from. Different types of paper sizes are available also in the library, here it’s A4 because it’s the most common size used for billing . You can also include custom fonts to make the PDF more
appealing to the user. In this example we used custom fonts and images to change the look and feel of the PDF.

screenshots
	public class MainActivity extends AppCompatActivity {
		private RecyclerView recyclerMoney;
		private ListAdapter listAdapter;
		private ArrayList listItems;
		private SwipeRefreshLayout swipeMoney;
		private MaterialButton buttonPdf;


		@Override
		protected void onCreate(Bundle savedInstanceState) {
			super.onCreate(savedInstanceState);
			setContentView(R.layout.activity_main);
			Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
			setSupportActionBar(toolbar);
			swipeMoney=findViewById(R.id.swipeMoney);
			recyclerMoney=findViewById(R.id.recyclerMoney);
			buttonPdf=findViewById(R.id.buttonPdf);

			FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
			fab.setOnClickListener(new View.OnClickListener() {
				@Override
				public void onClick(View view) {
					Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG)
							.setAction("Action", null).show();
				}
			});
			recyclerMoney.setHasFixedSize(true);
			recyclerMoney.setLayoutManager(new LinearLayoutManager(this));

			swipeMoney.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
				@Override
				public void onRefresh() {
					swipeMoney.setRefreshing(true);
					loadItems();
				}
			});

			swipeMoney.setRefreshing(true);
			loadItems();

			buttonPdf.setOnClickListener(new View.OnClickListener() {
				@Override
				public void onClick(View v) {
					AsyncMakePdf asyncMakePdf=new AsyncMakePdf();
					asyncMakePdf.execute(tempList());
				}
			});
		}


		public void loadItems(){
			listItems=new ArrayList();
			listItems=tempList();
			listAdapter=new ListAdapter(this,listItems);
			recyclerMoney.setAdapter(listAdapter);
			swipeMoney.setRefreshing(false);
		}



		public class AsyncMakePdf extends AsyncTask,String ,Integer>{

			AlertDialog dialogToShow;
			LayoutInflater inflater = getLayoutInflater();
			View view=inflater.inflate(R.layout.preloader_dialog,null);
			PlayGifView imgGif=view.findViewById(R.id.imgGif);
			TextView txtUpdate=view.findViewById(R.id.txtUpdate);
			AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);

			String path=FOLDER_PDF+File.separator+"Report.pdf";
			PdfWriter writer;

			@Override
			protected Integer doInBackground(ArrayList... arrayLists) {

				/**
				 * Creating Document for report
				 */

				BaseFont baseFont = null;
				try {
					baseFont = BaseFont.createFont("res/font/montserratregular.ttf", "UTF-8",BaseFont.EMBEDDED);
				} catch (IOException e) {
					e.printStackTrace();
				} catch (DocumentException e) {
					e.printStackTrace();
				}


				Font regularHead = new Font(baseFont, 15,Font.BOLD,BaseColor.WHITE);
				Font regularReport = new Font(baseFont, 30,Font.BOLD,printAccent);
				Font regularName = new Font(baseFont, 25,Font.BOLD,BaseColor.BLACK);
				Font regularAddress = new Font(baseFont, 15,Font.BOLD,BaseColor.BLACK);
				Font regularSub = new Font(baseFont, 12);
				Font regularTotal = new Font(baseFont, 16,Font.NORMAL,BaseColor.BLACK);
				Font regularTotalBold = new Font(baseFont, 16,Font.BOLD,BaseColor.BLACK);
				Font footerN = new Font(baseFont, 15,Font.BOLD,printAccent);
				Font footerE = new Font(baseFont, 12,Font.NORMAL,BaseColor.BLACK);


			 //   Document document = new Document(PageSize.A4);
				Document document = new Document(PageSize.A4, 36, 36, 36, 72);
				document.addCreationDate();
				document.addAuthor("Akhil");
				document.addCreator("logicchip.com");
				//document.setMargins(0,0,0,0);

	// Location to save
				try {
					writer =PdfWriter.getInstance(document, new FileOutputStream(path));
				} catch (DocumentException e) {
					e.printStackTrace();
				} catch (FileNotFoundException e) {
					e.printStackTrace();

				}




				PdfPTable tableFooter = new PdfPTable(1);
				tableFooter.setTotalWidth(523);

				PdfPCell footerName = new PdfPCell(new Phrase("LOGICCHIP",footerN));
				PdfPCell footerEmail = new PdfPCell(new Phrase("info@logicchip.com",footerE));

				PdfPCell footerEmpty = new PdfPCell(new Phrase(""));

				footerName.setBorder(Rectangle.NO_BORDER);
				footerEmpty.setBorder(Rectangle.NO_BORDER);
				footerEmail.setBorder(Rectangle.NO_BORDER);


				PdfPCell preBorderBlue = new PdfPCell(new Phrase(""));
				preBorderBlue.setMinimumHeight(5f);
				preBorderBlue.setUseVariableBorders(true);
				preBorderBlue.setBorder(Rectangle.TOP);
				preBorderBlue.setBorderColorTop(printPrimary);
				preBorderBlue.setBorderWidthTop(3);
				tableFooter.addCell(preBorderBlue);
				tableFooter.addCell(footerName);
				tableFooter.addCell(footerEmail);




				HeaderFooter event = new HeaderFooter(tableFooter);
				writer.setPageEvent(event);

				document.open();

				onProgressUpdate("Please wait...");


				PdfPCell preReport = new PdfPCell(new Phrase("REPORT",regularReport));


				preReport.setHorizontalAlignment(Element.ALIGN_RIGHT);
				preReport.setVerticalAlignment(Element.ALIGN_BOTTOM);
				preReport.setBorder(Rectangle.NO_BORDER);
				PdfPTable tableHeader = new PdfPTable(2);


				try {
					tableHeader.setWidths(new float[] { 1,3});
				} catch (DocumentException e) {
					e.printStackTrace();
				}

				try {
					Drawable d = getResources().getDrawable(R.drawable.logo);
					BitmapDrawable bitDw = ((BitmapDrawable) d);
					Bitmap bmp = bitDw.getBitmap();
					ByteArrayOutputStream stream = new ByteArrayOutputStream();
					bmp.compress(Bitmap.CompressFormat.PNG, 100, stream);
					Image image = Image.getInstance(stream.toByteArray());
					// image.scaleToFit(50, 50);
					PdfPCell preImage =     new PdfPCell(image, true);
					preImage.setBorder(Rectangle.NO_BORDER);

					tableHeader.addCell(preImage);
					tableHeader.addCell(preReport);

					document.add(tableHeader);

				} catch (BadElementException e) {
					e.printStackTrace();
				} catch (IOException e) {
					e.printStackTrace();
				} catch (DocumentException e) {
					e.printStackTrace();
				}




				PdfPTable tableHeading = new PdfPTable(2);
				tableHeading.setSpacingBefore(50);

				Date c = Calendar.getInstance().getTime();
				System.out.println("Current time => " + c);
				SimpleDateFormat df = new SimpleDateFormat("dd/MM/yyyy");
				String formattedDate = df.format(c);

				String theName="",theAddress="";

				theName="Name of person";
				theAddress="Address of person";

				PdfPCell preName = new PdfPCell(new Phrase(theName,regularName));
				PdfPCell preAddress = new PdfPCell(new Phrase(theAddress,regularAddress));
				PdfPCell preDate = new PdfPCell(new Phrase("DATE: "+formattedDate,regularAddress));
				PdfPCell preBill=new PdfPCell(new Phrase("No : 0001",regularAddress));

				preBill.setVerticalAlignment(Element.ALIGN_BOTTOM);
				preBill.setHorizontalAlignment(Element.ALIGN_RIGHT);

				preDate.setVerticalAlignment(Element.ALIGN_BOTTOM);
				preDate.setHorizontalAlignment(Element.ALIGN_RIGHT);
				preName.setBorder(Rectangle.NO_BORDER);
				preAddress.setBorder(Rectangle.NO_BORDER);
				preDate.setBorder(Rectangle.NO_BORDER);
				preBill.setBorder(Rectangle.NO_BORDER);

				try {
					tableHeading.addCell(preName);
					tableHeading.addCell(preBill);
					tableHeading.addCell(preAddress);
					tableHeading.addCell(preDate);
					document.add(tableHeading);
				} catch (DocumentException e) {
					e.printStackTrace();
				}




				PdfPTable table = new PdfPTable(4);
				table.setSpacingBefore(20);
				try {
					table.setWidths(new float[] { 1f,2, 3,1.5f});
				} catch (DocumentException e) {
					e.printStackTrace();
				}
				table.setHeaderRows(1);

				table.setSplitRows(false);
				table.setComplete(false);




				PdfPCell headDate = new PdfPCell(new Phrase("NO",regularHead));
				PdfPCell headName = new PdfPCell(new Phrase("ITEM",regularHead));
				PdfPCell headDis = new PdfPCell(new Phrase("COMPANY",regularHead));
				PdfPCell headCr = new PdfPCell(new Phrase("AMOUNT",regularHead));
				PdfPCell headDe = new PdfPCell(new Phrase("DEBIT",regularHead));

				headDate.setPaddingLeft(15);
				headDate.setPaddingTop(10);
				headDate.setPaddingBottom(14);
				headDate.setVerticalAlignment(Element.ALIGN_MIDDLE);

				headName.setPaddingTop(10);
				headName.setPaddingBottom(14);
				headName.setVerticalAlignment(Element.ALIGN_MIDDLE);

				headDis.setPaddingTop(10);
				headDis.setPaddingBottom(14);
				headDis.setVerticalAlignment(Element.ALIGN_MIDDLE);

				headCr.setPaddingTop(10);
				headCr.setPaddingBottom(14);
				headCr.setVerticalAlignment(Element.ALIGN_MIDDLE);

				headDe.setPaddingTop(10);
				headDe.setPaddingBottom(14);
				headDe.setVerticalAlignment(Element.ALIGN_MIDDLE);



				headDate.setBackgroundColor(printPrimary);
				headName.setBackgroundColor(printPrimary);
				headDis.setBackgroundColor(printPrimary);
				headCr.setBackgroundColor(printPrimary);
				headDe.setBackgroundColor(printPrimary);


				headDate.setBorder(Rectangle.NO_BORDER);
				headName.setBorder(Rectangle.NO_BORDER);
				headDis.setBorder(Rectangle.NO_BORDER);
				headCr.setBorder(Rectangle.NO_BORDER);
				headDe.setBorder(Rectangle.NO_BORDER);




				table.addCell(headDate);
				table.addCell(headName);
				table.addCell(headDis);
				table.addCell(headCr);


				int amountFull=0;
				for (int aw=0;aw



HeaderFooter

HeaderFooter.java class is used for creating footer of the PDF, so users can add there company name and email at the bottom of PDF.

public class HeaderFooter extends PdfPageEventHelper {
    private PdfPTable footer;
    public HeaderFooter(PdfPTable footer) {
        this.footer = footer;
    }
    public void onEndPage(PdfWriter writer, Document document) {
        footer.writeSelectedRows(0, -1, 36, 64, writer.getDirectContent());
    }
}

Create Whatsapp stickers

Its easy to create whatsapp stickers now, First you can download the demo from github which is provided by whatsapp.

Download
Github

First change the application id.

You can create your own stickers just follow below link.
whatsapp

Sticker files must be in WebP format, you can easily convert a png file to WebP from AndroidStudio itself.

Step 1

Add the image file (png format 512*512 size) in to the asset folder under a folder given. The folder name must be number alphabet etc.

STEp 2

Convert the image to WebP format.

step 3

For this step just add the identifier (folder name) and the image name (which is logicchip.webp) in contents.json.

its all done now just install the application.

Bottom Sheet implementation for Android – Logicchip

Bottom sheet is a component that slides up from bottom of the screen to reveal more content. You can find more detailed information of Bottom Sheet on Google Material Design guidelines.

Download

MainActivity

public class MainActivity extends AppCompatActivity {

    private AdapterColor adapterColor;
    private ArrayList<TypeColor> typeColors;
    private int posOfColor=0,posOfCountry=0;
    private String colorSelected="";
    private RecyclerView recycleViewDialog,recycleViewPersistent;
    private AdapterCountry adapterCountry;
    private ArrayList<TypeCountry> typeCountries;
    private ConstraintLayout constraintLayoutPersistent;
    private BottomSheetBehavior bottomSheetBehaviorPersistant;
    private ImageButton imgBtnUp;
    private AdapterPersistent adapterPersistent;
    private ArrayList<TypePersistent> typePersistents;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);
        constraintLayoutPersistent=(ConstraintLayout)findViewById(R.id.constraintLayoutPersistent);
        imgBtnUp=(ImageButton)findViewById(R.id.imgBtnUp);
        bottomSheetBehaviorPersistant=BottomSheetBehavior.from(constraintLayoutPersistent);
        recycleViewPersistent=(RecyclerView)findViewById(R.id.recycleViewPersistent);

        recycleViewPersistent.setHasFixedSize(true);
        recycleViewPersistent.setLayoutManager(new LinearLayoutManager(this));

        ForPersistent();

        bottomSheetBehaviorPersistant.setBottomSheetCallback(new BottomSheetBehavior.BottomSheetCallback() {
            @Override
            public void onStateChanged(@NonNull View bottomSheet, int newState) {

                if (newState==BottomSheetBehavior.STATE_EXPANDED){
                   if (imgBtnUp.getRotation()==0F){
                        //  btnBottomSheet.setText("Close Sheet");
                        float deg = imgBtnUp.getRotation() + 180F;
                        imgBtnUp.animate().rotation(deg).setInterpolator(new AccelerateDecelerateInterpolator());

                    }
                }
                switch (newState) {
                    case BottomSheetBehavior.STATE_HIDDEN:
                        break;
                    case BottomSheetBehavior.STATE_EXPANDED: {
                      //  btnBottomSheet.setText("Close Sheet");
                            //float deg = imgBtnUp.getRotation() + 180F;
                            //imgBtnUp.animate().rotation(deg).setInterpolator(new AccelerateDecelerateInterpolator());


                    }
                    break;
                    case BottomSheetBehavior.STATE_COLLAPSED: {
                      //  btnBottomSheet.setText("Expand Sheet");
if (imgBtnUp.getRotation()==180F){
    float deg = 0F;
     imgBtnUp.animate().rotation(deg).setInterpolator(new AccelerateDecelerateInterpolator());

}

                    }
                    break;
                    case BottomSheetBehavior.STATE_DRAGGING:
                        break;
                    case BottomSheetBehavior.STATE_SETTLING:
                        break;
                }
            }

            @Override
            public void onSlide(@NonNull View bottomSheet, float slideOffset) {
            //    Toast.makeText(MainActivity.this,"Slide",Toast.LENGTH_SHORT).show();
            }
        });

    }

    public void ForPersistent(){

        typePersistents=new ArrayList<TypePersistent>();
        typePersistents.add(new TypePersistent("Hospital",R.drawable.ic_local_hospital));
        typePersistents.add(new TypePersistent("Fuel Station",R.drawable.ic_ev_station));
        typePersistents.add(new TypePersistent("ATM",R.drawable.ic_local_atm));
        typePersistents.add(new TypePersistent("Restaurant",R.drawable.ic_restaurant));
        typePersistents.add(new TypePersistent("Movies",R.drawable.ic_local_movies));
        adapterPersistent=new AdapterPersistent(MainActivity.this,typePersistents);
        recycleViewPersistent.setAdapter(adapterPersistent);
    }

    public void toggleBottomSheet(View view) {
        if (bottomSheetBehaviorPersistant.getState() != BottomSheetBehavior.STATE_EXPANDED) {
            float deg = imgBtnUp.getRotation() + 180F;
            imgBtnUp.animate().rotation(deg).setInterpolator(new AccelerateDecelerateInterpolator());

            bottomSheetBehaviorPersistant.setState(BottomSheetBehavior.STATE_EXPANDED);
            //btnBottomSheet.setText("Close sheet");
        } else {
            bottomSheetBehaviorPersistant.setState(BottomSheetBehavior.STATE_COLLAPSED);
            //btnBottomSheet.setText("Expand sheet");

            float deg = 0F;
            imgBtnUp.animate().rotation(deg).setInterpolator(new AccelerateDecelerateInterpolator());

        }
    }

    public void BottomSheetDialog(View view){
        typeCountries=new ArrayList<TypeCountry>();
        typeCountries.add(new TypeCountry("India",false));
        typeCountries.add(new TypeCountry("United States",false));
        typeCountries.add(new TypeCountry("China",false));
        typeCountries.add(new TypeCountry("Spain",false));
        typeCountries.add(new TypeCountry("Germany",false));
        typeCountries.add(new TypeCountry("Argentina",false));
        typeCountries.add(new TypeCountry("Brazil",false));
        typeCountries.add(new TypeCountry("Canada",false));
        typeCountries.add(new TypeCountry("Dubai",false));
        typeCountries.add(new TypeCountry("Mexico",false));

        adapterCountry=new AdapterCountry(this,typeCountries);


        View vu= getLayoutInflater().inflate(R.layout.bottom_sheet_dialog, null);
        recycleViewDialog=(RecyclerView)vu.findViewById(R.id.recycleViewDialog);
        recycleViewDialog.setHasFixedSize(true);
        recycleViewDialog.setLayoutManager(new LinearLayoutManager(this));
        recycleViewDialog.setAdapter(adapterCountry);
        BottomSheetDialog dialog = new BottomSheetDialog(this);
        dialog.setContentView(vu);
        dialog.show();
        SelectCountry(posOfCountry);
    }

    public void SelectCountry(int pos){
        posOfCountry=pos;

        for (int i=0;i<typeCountries.size();i++){
            if (typeCountries.get(i).isSelected()){
                typeCountries.get(i).setSelected(false);
                adapterCountry.notifyItemChanged(i);
            }
        }

        //adapterItemThumb.notifyDataSetChanged();
        typeCountries.get(pos).setSelected(true);
        adapterCountry.notifyItemChanged(pos);

    }

    public void BottomSheetFragment(View view){
        typeColors=new ArrayList<TypeColor>();
        typeColors.add(new TypeColor("Red","#d32f2f",true));
        typeColors.add(new TypeColor("Pink","#c2185b",false));
        typeColors.add(new TypeColor("Purple","#7b1fa2",false));
        typeColors.add(new TypeColor("Deep Purple","#512da8",false));
        typeColors.add(new TypeColor("Indigo","#303f9f",false));
        typeColors.add(new TypeColor("Blue","#1976d2",false));
        typeColors.add(new TypeColor("Light blue","#0288d1",false));
        typeColors.add(new TypeColor("Cyan","#0097a7",false));
        typeColors.add(new TypeColor("Teal","#00796b",false));
        typeColors.add(new TypeColor("Green","#388e3c",false));
        typeColors.add(new TypeColor("Light green","#689f38",false));
        typeColors.add(new TypeColor("Lime","#afb42b",false));
        typeColors.add(new TypeColor("Yellow","#fbc02d",false));
        typeColors.add(new TypeColor("Amber","#ffa000",false));
        typeColors.add(new TypeColor("Orange","#f57c00",false));
        typeColors.add(new TypeColor("Deep orange","#e64a19",false));
        typeColors.add(new TypeColor("Brown","#5d4037",false));
        typeColors.add(new TypeColor("Gray","#616161",false));
        typeColors.add(new TypeColor("Blue Gray","#455a64",false));

        FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();

        BottomSheetColor.newInstance(typeColors).show(transaction, "colorFragment");
       // SelectPosition();
    }

    public void SelectPosition(){
        BottomSheetColor  bottomSheetColor=(BottomSheetColor)getSupportFragmentManager().findFragmentByTag("colorFragment");
        bottomSheetColor.addSelection(posOfColor);
    }

    public void ColorSelect(TypeColor typeColor,int pos){
        BottomSheetColor  bottomSheetColor=(BottomSheetColor)getSupportFragmentManager().findFragmentByTag("colorFragment");
         bottomSheetColor.addSelection(pos);
         posOfColor=pos;
        //bottomSheetColor.dismiss();
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.menu_main, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();

        //noinspection SimplifiableIfStatement
        if (id == R.id.action_settings) {
            return true;
        }

        return super.onOptionsItemSelected(item);
    }


}

ActivityMain xml

<?xml version="1.0" encoding="utf-8"?>
<android.support.design.widget.CoordinatorLayout 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=".MainActivity">

    <android.support.design.widget.AppBarLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:theme="@style/AppTheme.AppBarOverlay">

        <android.support.v7.widget.Toolbar
            android:id="@+id/toolbar"
            android:layout_width="match_parent"
            android:layout_height="?attr/actionBarSize"
            android:background="?attr/colorPrimary"
            app:popupTheme="@style/AppTheme.PopupOverlay" />

    </android.support.design.widget.AppBarLayout>

    <include layout="@layout/content_main" />

    <!-- Adding bottom sheet after main content -->
    <include layout="@layout/bottom_sheet_persistent" />
</android.support.design.widget.CoordinatorLayout>

ContentMain 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"
    app:layout_behavior="@string/appbar_scrolling_view_behavior"
    tools:context=".MainActivity"
    tools:showIn="@layout/activity_main">
    <RelativeLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content">
        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:orientation="vertical">


            <Button
                android:textAllCaps="false"
                android:onClick="toggleBottomSheet"
                android:layout_gravity="center"
                style="@style/Base.Widget.AppCompat.Button.Colored"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text="Persistent bottom sheet"/>
            <Button
                android:textAllCaps="false"
                android:onClick="BottomSheetDialog"
                android:layout_gravity="center"
                style="@style/Base.Widget.AppCompat.Button.Colored"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text="Dialog bottom sheet"/>
            <Button
                android:textAllCaps="false"
                android:onClick="BottomSheetFragment"
                android:layout_gravity="center"
                style="@style/Base.Widget.AppCompat.Button.Colored"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text="Fragment bottom sheet"/>
        </LinearLayout>
    </RelativeLayout>


</android.support.constraint.ConstraintLayout>

Dynamically add Multiple Runtime Permission

Permission are a thing now. Presently from Marshmallow on words android require Additional runtime permissions. Above all in order to work properly it’s essential. You know what  mean. Presumably we specify each permissions multiple times in a class. However this tutorial is about adding multiple permissions dynamically.Yes that’s right.First Place all the required permissions in an array then call a method it’s that simple. As a matter of fact Only devices above Marshmallow have runtime permissions.  You must keep in mind that to.

Permission

There are two types of permissions.

  1. Normal permissions
  2. Dangerous permissions
1- Normal permission

Presently those permissions the system automatically grants to your app.Permissions Like internet.

2-Dangerous permissions

Similarly those permissions user must agree to grand. Examples are permissions for location ,sms etc…

Download source code for free

Source code

Finally you only need to add which permissions to request in the string array.

String[] permissionList = new String[]{
            Manifest.permission.SEND_SMS,
            Manifest.permission.ACCESS_FINE_LOCATION,
            Manifest.permission.CAMERA};

 

 

PermissionActivity.java

public class PermissionActivity extends AppCompatActivity {
    String[] permissionList = new String[]{
            Manifest.permission.SEND_SMS,
            Manifest.permission.ACCESS_FINE_LOCATION,
            Manifest.permission.CAMERA};

    private boolean isSettings = false;

    private static final int PERMISSION_CALLBACK = 111;
    private static final int PERMISSION_REQUEST = 222;



    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_permission);
        if (Build.VERSION.SDK_INT>= Build.VERSION_CODES.M){
            ChkPerm();
        }else{
            noPermission();
        }
    }

    private void noPermission() {
        //devices below Marshmellow
        Intent intent=new Intent(PermissionActivity.this,MainActivity.class);
        intent.putExtra("isAbove",false);
        startActivity(intent);
        finish();
    }

    private void afterPermission() {
        Intent intent=new Intent(PermissionActivity.this,MainActivity.class);
        intent.putExtra("isAbove",true);
        startActivity(intent);
        finish();
    }


    public void ChkPerm(){
        if(forSelfPermission()){

            if(shouldShow()){
                permissionCallBack();
            }  else {
                //just request the permission
                ActivityCompat.requestPermissions(PermissionActivity.this,permissionList, PERMISSION_CALLBACK);
            }
        } else {
            //You already have the permission, just go ahead.
            afterPermission();
        }
    }



    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        if(requestCode == PERMISSION_CALLBACK){
            //check if all permissions are granted
            boolean allgranted = false;
            for(int i=0;i<grantResults.length;i++){
                if(grantResults[i]==PackageManager.PERMISSION_GRANTED){
                    allgranted = true;
                } else {
                    allgranted = false;
                    break;
                }
            }

            if(allgranted){
                afterPermission();
            } else if(shouldShow()){

                permissionCallBack();
            } else {

                permissionSettings();
                Toast.makeText(getBaseContext(),"Unable to get Permission", Toast.LENGTH_LONG).show();
            }
        }
    }



    private boolean forSelfPermission(){
        boolean allgranted = false;
        for(int i=0;i<permissionList.length;i++){

            if (ActivityCompat.checkSelfPermission(PermissionActivity.this, permissionList[i]) != PackageManager.PERMISSION_GRANTED) {
                allgranted = true;
                break;
            } else {
                allgranted = false;
            }
        }

        if (allgranted){
            return true;
        }else{
            return false;
        }

    }

    private boolean resultPermission(){
        boolean allgranted = false;
        for(int i=0;i<permissionList.length;i++){

            if (ActivityCompat.checkSelfPermission(PermissionActivity.this, permissionList[i]) == PackageManager.PERMISSION_GRANTED) {
                allgranted = true;
            } else {
                allgranted = false;
                break;
            }
        }

        if (allgranted){
            return true;
        }else{
            return false;
        }

    }


    private boolean shouldShow(){

        boolean allgranted = false;
        for(int i=0;i<permissionList.length;i++){
            if (ActivityCompat.shouldShowRequestPermissionRationale(PermissionActivity.this, permissionList[i])) {
                allgranted = true;
                break;
            } else {
                allgranted = false;
            }
        }

        if (allgranted){
            return true;
        }else{
            return false;
        }
    }

    private void permissionCallBack(){
        AlertDialog.Builder builder = new AlertDialog.Builder(PermissionActivity.this);
        builder.setTitle("Need Multiple Permissions");
        builder.setMessage("This app needs Multiple permissions.");
        builder.setPositiveButton("Grant", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                dialog.cancel();
                ActivityCompat.requestPermissions(PermissionActivity.this,permissionList, PERMISSION_CALLBACK);
            }
        });
        builder.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                dialog.cancel();
            }
        });
        builder.show();

    }

    private void permissionSettings(){
        AlertDialog.Builder builder = new AlertDialog.Builder(PermissionActivity.this);
        builder.setTitle("Need Multiple Permissions");
        builder.setMessage("This app needs permission allow them from settings.");
        builder.setPositiveButton("Settings", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                dialog.cancel();
                isSettings = true;
                Intent intent = new Intent(Settings.ACTION_APPLICATION_DETAILS_SETTINGS);
                Uri uri = Uri.fromParts("package", getPackageName(), null);
                intent.setData(uri);
                startActivityForResult(intent, PERMISSION_REQUEST);
                // Toast.makeText(getBaseContext(), "Go to Permissions to Grant  Camera and Location", Toast.LENGTH_LONG).show();
            }
        });
        builder.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                dialog.cancel();
            }
        });
        builder.show();

    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        Log.d("R","result");
        if (requestCode == PERMISSION_REQUEST) {

            if (resultPermission()){
                Log.d("R","result s");
                afterPermission();
            }else{
                Log.d("R","result c");
                ChkPerm();
            }

        }
    }



    @Override
    protected void onPostResume() {
        super.onPostResume();
        if (isSettings) {
            Log.d("R","resume");
            if (resultPermission()){
                Log.d("R","resume s");
                afterPermission();
            }else{
                Log.d("R","resume c");
                ChkPerm();
            }

            isSettings=false;
        }
    }
}

 

You can check out Dynamic Action Bar color

Dynamic Action Bar and Status bar Color

Action bar color dynamically. Sometimes it is necessary to change the Action Bar and status bar color dynamically. This project shows how it can be achieved simply. Status bar color change is supported for lollipop and  above devices. So the project works by checking build versions of the device.Only action-bar color is can be changed for devices below lollipop and both action bar and status-bar color are changeable for devices above lollipop, else app crashes. To give an overview activity contain three seek-bars each representing the primary colors Red,Blue and Green. The goal is to create our required color by combining these colors. For the first step is to check the build version of the device. if it’s below lollipop the default color is set, and  if it’s above lollipop default status-bar color also applied.

Changes made to the seek-bar are being saved so when you reopen the app the color is the last one you selected. You can modify the code as you like “link to source code is down below”.  Now straight to code because it’s simple and nothing more to say about it.

DOWNLOAD HERE

 

MainActivity.java

public class MainActivity extends AppCompatActivity {
    SeekBar seekBarRed,seekBarGreen,seekBarBlue;
    RadioGroup idForRadioGroup;
    TextView textR,textG,textB;
    private SharedPreferences sharedPreferences;
    private SharedPreferences.Editor editor;
    private boolean bar=true;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        idForRadioGroup=(RadioGroup)findViewById(R.id.idForRadioGroup);
        RadioButton rButton = (RadioButton) idForRadioGroup.getChildAt(0);
        rButton.setChecked(true);

        RadioButton rButton2 = (RadioButton) idForRadioGroup.getChildAt(1);
        rButton2.setVisibility(View.GONE);

        sharedPreferences = getSharedPreferences("key_clr", Context.MODE_PRIVATE);
        editor=sharedPreferences.edit();

        textR=(TextView)findViewById(R.id.textR);
        textG=(TextView)findViewById(R.id.textG);
        textB=(TextView)findViewById(R.id.textB);

        seekBarRed=(SeekBar)findViewById(R.id.seekBarRed);
        seekBarGreen=(SeekBar)findViewById(R.id.seekBarGreen);
        seekBarBlue=(SeekBar)findViewById(R.id.seekBarBlue);
        getClr();
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            rButton2.setVisibility(View.VISIBLE);
            initStatusBarClr();
        }

        idForRadioGroup.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener()
        {
            public void onCheckedChanged(RadioGroup group, int checkedId) {
                switch(checkedId){
                    case R.id.radio0:
                        // do operations specific to this selection
                        bar=true;
                        getClr();
                        break;
                    case R.id.radio1:
                        // do operations specific to this selection
                        bar=false;
                        getClr();
                        break;
                }
            }
        });


        seekBarRed.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
            @Override
            public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
                textR.setText("= "+String.valueOf(progress));
                putClr();
            }
            @Override
            public void onStartTrackingTouch(SeekBar seekBar) {
            }
            @Override
            public void onStopTrackingTouch(SeekBar seekBar) {
            }
        });

        seekBarGreen.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
            @Override
            public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
                textG.setText("= "+String.valueOf(progress));
                putClr();
            }
            @Override
            public void onStartTrackingTouch(SeekBar seekBar) {
            }
            @Override
            public void onStopTrackingTouch(SeekBar seekBar) {
            }
        });

        seekBarBlue.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
            @Override
            public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
                textB.setText("= "+String.valueOf(progress));
                putClr();
            }
            @Override
            public void onStartTrackingTouch(SeekBar seekBar) {
            }
            @Override
            public void onStopTrackingTouch(SeekBar seekBar) {
            }
        });

    }

    public void ActionBarClr(){
        getSupportActionBar().setBackgroundDrawable(
                new ColorDrawable(Color.rgb(seekBarRed.getProgress()
                ,seekBarGreen.getProgress(),seekBarBlue.getProgress())));
    }
    
    public void StatusBarClr(){     
        Window window = this.getWindow();
// clear FLAG_TRANSLUCENT_STATUS flag:
        window.clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
// add FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS flag to the window
        window.addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS);
// finally change the color
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
        //    window.setStatusBarColor(Color.BLUE);

         window.setStatusBarColor(Color.rgb(seekBarRed.getProgress()
                ,seekBarGreen.getProgress(),seekBarBlue.getProgress()));
        }
    }


    public void initStatusBarClr(){

        int r=sharedPreferences.getInt("s_r",0);
        int g=sharedPreferences.getInt("s_g",0);
        int b=sharedPreferences.getInt("s_b",0);

        Window window = this.getWindow();
// clear FLAG_TRANSLUCENT_STATUS flag:
        window.clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
// add FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS flag to the window
        window.addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS);
// finally change the color
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
//    window.setStatusBarColor(Color.BLUE);
            window.setStatusBarColor(Color.rgb(r,g,b));
        }


    }

    public void getClr(){
        if(bar) {
            int r=sharedPreferences.getInt("a_r",0);
            int g=sharedPreferences.getInt("a_g",0);
            int b=sharedPreferences.getInt("a_b",0);

            seekBarRed.setProgress(r);
            seekBarGreen.setProgress(g);
            seekBarBlue.setProgress(b);

            textR.setText("= "+String.valueOf(r));
            textG.setText("= "+String.valueOf(g));
            textB.setText("= "+String.valueOf(b));
            ActionBarClr();
        }else{
            int r=sharedPreferences.getInt("s_r",0);
            int g=sharedPreferences.getInt("s_g",0);
            int b=sharedPreferences.getInt("s_b",0);

            seekBarRed.setProgress(r);
            seekBarGreen.setProgress(g);
            seekBarBlue.setProgress(b);

            textR.setText("= "+String.valueOf(r));
            textG.setText("= "+String.valueOf(g));
            textB.setText("= "+String.valueOf(b));
            StatusBarClr();
        }
    }

    public void putClr(){
        if (bar){
            editor.putInt("a_r",seekBarRed.getProgress());
            editor.putInt("a_g",seekBarGreen.getProgress());
            editor.putInt("a_b",seekBarBlue.getProgress());
            editor.commit();
            ActionBarClr();
        }else{
            editor.putInt("s_r",seekBarRed.getProgress());
            editor.putInt("s_g",seekBarGreen.getProgress());
            editor.putInt("s_b",seekBarBlue.getProgress());
            editor.commit();
            StatusBarClr();
        }
    }
}

Now for the activity xml part

activity_main.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"
    tools:context="com.logicchip.blog_18_dynamic_action_bar_color.MainActivity">
    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="vertical">

        <RadioGroup
            android:id="@+id/idForRadioGroup"
            android:layout_margin="16dp"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:orientation="horizontal">
            <RadioButton
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text="Action bar"
                android:id="@+id/radio0"/>
            <RadioButton
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text="Status Bar"
                android:id="@+id/radio1"/>
        </RadioGroup>

        <LinearLayout
            android:layout_margin="16dp"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:orientation="horizontal">
            <TextView
                android:gravity="center"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:text="R"
                android:textSize="20sp"
                android:textStyle="bold"
                android:layout_weight="1"/>
            <TextView
                android:gravity="left"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:text="= 000"
                android:id="@+id/textR"
                android:layout_weight="1"/>
            <TextView
                android:gravity="center"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:text="G"
                android:textSize="20sp"
                android:textStyle="bold"
                android:layout_weight="1"/>
            <TextView
                android:gravity="left"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:text="= 000"
                android:id="@+id/textG"
                android:layout_weight="1"/>
            <TextView
                android:gravity="center"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:text="B"
                android:textSize="20sp"
                android:textStyle="bold"
                android:layout_weight="1"/>
            <TextView
                android:gravity="left"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:text="= 000"
                android:id="@+id/textB"
                android:layout_weight="1"/>
        </LinearLayout>
        <SeekBar
            android:layout_margin="16dp"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:id="@+id/seekBarRed"
            android:max="255"
            android:theme="@style/redTheme"/>
        <SeekBar
            android:layout_margin="16dp"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:id="@+id/seekBarGreen"
            android:theme="@style/greenTheme"
            android:max="255"/>
        <SeekBar
            android:layout_margin="16dp"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:id="@+id/seekBarBlue"
            android:theme="@style/blueTheme"
            android:max="255"/>

    </LinearLayout>

</RelativeLayout>

 

 

Custom Android Navigation Drawer

Here ,I will show you how to create a custom Navigation Drawer using the auto generated Android Studio Navigation Drawer template. Using the auto generated Android Studio Navigation Drawer gives you are great head start for most of the use cases of Navigation Drawer; however it can also leave you in the middle of nowhere if you want to apply some customization. Here is what our demo app will look like when completed.[the_ad id=”1065″]

Adding Navigation Drawer

Create a new Android project using Android Studio, Select the new project template, select Phone and Tablet as your target devices and choose any API level 16.  Click next and select Activity with Navigation like the image below and click next.[the_ad id=”1065″]

ject, I have added the following Fragments. No functionality is actually implemented in these fragments, they are used as demo fragment to demonstrate Navigation Drawer

  1. FragmentA
  2. FragmentB
  3. FragmentC
  4. FragmentD

Screen shots

MainActivity

public class MainActivity extends AppCompatActivity
        implements NavigationView.OnNavigationItemSelectedListener {
    private LinearLayout clk1,clk2,clk3,clk4;
    TextView textMatter;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);

        textMatter=(TextView)findViewById(R.id.textMatter);

        clk1=(LinearLayout)findViewById(R.id.click1);
        clk2=(LinearLayout)findViewById(R.id.click2);
        clk3=(LinearLayout)findViewById(R.id.click3);
        clk4=(LinearLayout)findViewById(R.id.click4);
        Initializing();
        DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
        ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(
                this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
        drawer.addDrawerListener(toggle);
        toggle.syncState();
    }

    @Override
    public void onBackPressed() {
        DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
        if (drawer.isDrawerOpen(GravityCompat.START)) {
            drawer.closeDrawer(GravityCompat.START);
        } else {
            super.onBackPressed();
        }
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.main, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();

        //noinspection SimplifiableIfStatement
        if (id == R.id.action_nine) {
            textMatter.setText("99");
            return true;
        }if (id == R.id.action_two) {
            textMatter.setText("22");
            return true;
        }

        return super.onOptionsItemSelected(item);
    }


    public void Initializing(){
        Fragment fragment = null;
        Class fragmentClass =  FragmentA.class;
        try {
            fragment = (Fragment) fragmentClass.newInstance();
        } catch (Exception e) {
            e.printStackTrace();
        }// Insert the fragment by replacing any existing fragment
        FragmentManager fragmentManager = getSupportFragmentManager();
        fragmentManager.beginTransaction().replace(R.id.frame, fragment).commit();
    }
    public void ClickNavigation(View view){
        Fragment fragment = null;
        Class fragmentClass =  FragmentA.class;

        switch (view.getId()){
            case R.id.click1:
                fragmentClass = FragmentA.class;
                clk1.setBackground(ResourcesCompat.getDrawable(getResources(), R.drawable.button_clickb, null));
                clk2.setBackground(ResourcesCompat.getDrawable(getResources(), R.drawable.button_click, null));
                clk3.setBackground(ResourcesCompat.getDrawable(getResources(), R.drawable.button_click, null));
                clk4.setBackground(ResourcesCompat.getDrawable(getResources(), R.drawable.button_click, null));
                break;
            case R.id.click2:
                fragmentClass = FragmentB.class;
                clk1.setBackground(ResourcesCompat.getDrawable(getResources(), R.drawable.button_click, null));
                clk2.setBackground(ResourcesCompat.getDrawable(getResources(), R.drawable.button_clickb, null));
                clk3.setBackground(ResourcesCompat.getDrawable(getResources(), R.drawable.button_click, null));
                clk4.setBackground(ResourcesCompat.getDrawable(getResources(), R.drawable.button_click, null));
                break;
            case R.id.click3:
                fragmentClass = FragmentC.class;
                clk1.setBackground(ResourcesCompat.getDrawable(getResources(), R.drawable.button_click, null));
                clk2.setBackground(ResourcesCompat.getDrawable(getResources(), R.drawable.button_click, null));
                clk3.setBackground(ResourcesCompat.getDrawable(getResources(), R.drawable.button_clickb, null));
                clk4.setBackground(ResourcesCompat.getDrawable(getResources(), R.drawable.button_click, null));
                break;
            case R.id.click4:
                fragmentClass = FragmentD.class;
                clk1.setBackground(ResourcesCompat.getDrawable(getResources(), R.drawable.button_click, null));
                clk2.setBackground(ResourcesCompat.getDrawable(getResources(), R.drawable.button_click, null));
                clk3.setBackground(ResourcesCompat.getDrawable(getResources(), R.drawable.button_click, null));
                clk4.setBackground(ResourcesCompat.getDrawable(getResources(), R.drawable.button_clickb, null));
                break;
        }
        try {
            fragment = (Fragment) fragmentClass.newInstance();
        } catch (Exception e) {
            e.printStackTrace();
        }// Insert the fragment by replacing any existing fragment
        FragmentManager fragmentManager = getSupportFragmentManager();
        fragmentManager.beginTransaction().replace(R.id.frame, fragment).commit();

        DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
        drawer.closeDrawer(GravityCompat.START);
    }
}

activity_main

As you can see below we commented the NavigationView and replaced it with Our LinearLayout.

<?xml version="1.0" encoding="utf-8"?>
<android.support.v4.widget.DrawerLayout 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:id="@+id/drawer_layout"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:fitsSystemWindows="true"
    tools:openDrawer="start">

    <include
        layout="@layout/app_bar_main"
        android:layout_width="match_parent"
        android:layout_height="match_parent" />

    <!--<android.support.design.widget.NavigationView
        android:id="@+id/nav_view"
        android:layout_width="wrap_content"
        android:layout_height="match_parent"
        android:layout_gravity="start"
        android:fitsSystemWindows="true"
        app:headerLayout="@layout/nav_header_main"
        app:menu="@menu/activity_main_drawer" />
-->

    <LinearLayout
        android:background="@color/colorPrimaryText"
        android:id="@+id/drawer"
        android:layout_width="100dp"
        android:layout_height="wrap_content"
        android:layout_gravity="start"
        android:orientation="vertical">
        <ScrollView
            android:layout_width="match_parent"
            android:layout_height="wrap_content">

            <LinearLayout
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:orientation="vertical">
                <ImageView
                    android:onClick="ClickNavigation"
                    android:background="@color/colorPrimary"
                    android:layout_gravity="center"
                    android:gravity="center"
                    android:drawablePadding="5dp"
                    android:padding="10dp"
                    android:src="@mipmap/ic_launcher"
                    android:layout_width="match_parent"
                    android:layout_height="55dp"/>

                <LinearLayout
                    android:id="@+id/click1"
                    android:onClick="ClickNavigation"
                    android:background="@drawable/button_click"
                    android:layout_width="match_parent"
                    android:layout_height="100dp"
                    android:gravity="center"
                    android:orientation="vertical">
                    <RelativeLayout
                        android:layout_width="wrap_content"
                        android:layout_height="wrap_content">
                        <TextView
                            android:layout_marginLeft="70dp"
                            android:layout_marginTop="10dp"
                            android:background="@drawable/number"
                            android:layout_width="5dp"
                            android:layout_height="5dp"
                            android:text=""/>

                        <ImageView
                            android:tint="@color/icons"
                            android:padding="10dp"
                            android:src="@drawable/ic_menu_camera"
                            android:layout_width="match_parent"
                            android:layout_height="wrap_content"
                            android:text="Home"/>
                    </RelativeLayout>
                    <TextView
                        android:textColor="@color/icons"
                        android:layout_gravity="center"
                        android:layout_width="wrap_content"
                        android:layout_height="wrap_content"
                        android:text="Camera"/>
                </LinearLayout>

                <LinearLayout
                    android:id="@+id/click2"
                    android:onClick="ClickNavigation"
                    android:background="@drawable/button_click"
                    android:layout_width="match_parent"
                    android:layout_height="100dp"
                    android:gravity="center"
                    android:orientation="vertical">
                    <RelativeLayout
                        android:layout_width="wrap_content"
                        android:layout_height="wrap_content">
                    <TextView
                        android:textColor="@color/icons"
                        android:layout_marginLeft="75dp"
                        android:layout_marginTop="5dp"
                        android:background="@drawable/number"
                        android:layout_width="wrap_content"
                        android:layout_height="wrap_content"
                        android:padding="3dp"
                        android:id="@+id/textMatter"
                        android:text="22"/>
                    <ImageView
                        android:tint="@color/icons"
                        android:padding="10dp"
                        android:src="@drawable/ic_menu_gallery"
                        android:layout_width="match_parent"
                        android:layout_height="wrap_content"
                        android:text="Import"/>
                    </RelativeLayout>
                    <TextView
                        android:textColor="@color/icons"
                        android:layout_gravity="center"
                        android:layout_width="wrap_content"
                        android:layout_height="wrap_content"
                        android:text="Gallery"/>
                </LinearLayout>

                <LinearLayout
                    android:id="@+id/click3"
                    android:onClick="ClickNavigation"
                    android:background="@drawable/button_click"
                    android:layout_width="match_parent"
                    android:layout_height="100dp"
                    android:gravity="center"
                    android:orientation="vertical">
                    <ImageView
                        android:tint="@color/icons"
                        android:padding="10dp"
                        android:src="@drawable/ic_menu_manage"
                        android:layout_width="match_parent"
                        android:layout_height="wrap_content"
                        android:text="Home"/>
                    <TextView
                        android:textColor="@color/icons"
                        android:layout_gravity="center"
                        android:layout_width="wrap_content"
                        android:layout_height="wrap_content"
                        android:text="Tools"/>
                </LinearLayout>

                <LinearLayout
                    android:id="@+id/click4"
                    android:onClick="ClickNavigation"
                    android:background="@drawable/button_click"
                    android:layout_width="match_parent"
                    android:layout_height="100dp"
                    android:gravity="center"
                    android:orientation="vertical">

                    <ImageView
                        android:tint="@color/icons"
                        android:padding="10dp"
                        android:src="@drawable/ic_menu_send"
                        android:layout_width="match_parent"
                        android:layout_height="wrap_content"
                        android:text="Home"/>
                    <TextView
                        android:textColor="@color/icons"
                        android:layout_gravity="center"
                        android:layout_width="wrap_content"
                        android:layout_height="wrap_content"
                        android:text="Send"/>
                </LinearLayout>
            </LinearLayout>

        </ScrollView>
    </LinearLayout>
</android.support.v4.widget.DrawerLayout>

button_click

<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:state_pressed="false">
        <shape android:shape="rectangle">
            <solid android:color="@color/colorPrimaryText" />
        </shape>
    </item>
    <item android:state_pressed="true">
        <shape android:shape="rectangle" >
            <solid android:color="@color/clr2"/>
        </shape>
    </item>
    <item android:state_hovered="true">
        <shape android:shape="rectangle" >
            <solid android:color="@color/clr2"/>
        </shape>
    </item>
</selector>

button_clickb

<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:state_pressed="false">
        <shape android:shape="rectangle">
            <solid android:color="@color/clr2" />
        </shape>
    </item>

</selector>

 

You can download full code from here, You can modify the code us u like. In like manner feel free to comment your doubt’s below. Does our tutorials help you then help as spread the word, like and share.

Widget Creating in Android Studio

App Widget are miniature application views that can be embedded in other applications (such as the Home screen) and receive periodic updates. These views are referred to as Widgets in the user interface, and you can publish one with an AppWidget provider. An application component that is able to hold other App Widgets is called an AppWidget host.


The Basics


To create an AppWidget, you need the following:

AppWidgetProviderInfo object
Describes the metadata for an AppWidget, such as the App Widget’s layout, update frequency, and the AppWidgetProvider class. This should be defined in XML.
AppWidgetProvider class implementation
Defines the basic methods that allow you to programmatically interface with the AppWidget, based on broadcast events. Through it, you will receive broadcasts when the App Widget is updated, enabled, disabled and deleted.

Adding the AppWidgetProviderInfo Metadata


The AppWidgetProviderInfo defines the essential qualities of an App Widget, such as its minimum layout dimensions, its initial layout resource, how often to update the App Widget, and (optionally) a configuration Activity to launch at create-time. Define the AppWidgetProviderInfo object in an XML resource using a single <appwidget-provider> element and save it in the project’s res/xml/ folder.

<?xml version="1.0" encoding="utf-8"?>
<appwidget-provider xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:initialKeyguardLayout="@layout/widget"
    android:initialLayout="@layout/widget"
    android:minHeight="40dp"
    android:minWidth="250dp"
    android:previewImage="@drawable/ic_launcher"
    android:updatePeriodMillis="1000"
    android:widgetCategory="keyguard|home_screen"
    tools:ignore="UnusedAttribute" >
</appwidget-provider>



Declaring an App Widget in the Manifest


First, declare the AppWidgetProvider class in your application’s AndroidManifest.xml file. For example:

<receiver android:name=".AppWidgetObject"
            android:label="@string/widget_name">
            <intent-filter>
                <action android:name="android.appwidget.action.APPWIDGET_UPDATE" />
            </intent-filter>

            <meta-data
                android:name="android.appwidget.provider"
                android:resource="@xml/widget_info" />
        </receiver>
        <service android:name=".AppWidgetObject$UpdateService" />

Creating the App Widget Layout


You must define an initial layout for your AppWidget in XML and save it in the project’s res/layout/ directory. You can design your AppWidget using the View objects listed below, but before you begin designing your AppWidget, please read and understand the AppWidget Design Guidelines.

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:orientation="vertical">
    <TextView
        android:textSize="30dp"
        android:id="@+id/idForTimeChange"
        android:layout_gravity="center"
        android:layout_width="wrap_content"
        android:layout_height="50dp"
        android:text="00 : 00 : 00"/>

    <TextView
        android:textColor="@color/colorAccentLight"
        android:layout_gravity="center"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="logicchip.com"/>
</LinearLayout>

Using the AppWidgetProvider Class


public class AppWidgetObject extends AppWidgetProvider {

    private Handler handler;
    private Runnable runnable;
    SimpleDateFormat simpleDateFormat;
    String time;
    Calendar calander;
    Context context;


    @Override
    public void onUpdate(Context context, AppWidgetManager appWidgetManager, int[] appWidgetIds)
    {
        context.startService(new Intent(context, UpdateService.class));
    }



    public static class UpdateService extends Service {
        private Handler handler;
        private Runnable runnable;
        SimpleDateFormat simpleDateFormat;
        String time;
        Calendar calander;

        @Override
        public int onStartCommand(Intent intent, int flags, int startId) {
            TimeForUpdate();
            return START_REDELIVER_INTENT;
        }


        @Nullable
        @Override
        public IBinder onBind(Intent intent) {
            return null;
        }


        public void TimeForUpdate(){
            handler = new Handler();
            runnable = new Runnable() {
                @Override
                public void run() {
                    handler.postDelayed(this, 1000);
                    try {

                        calander = Calendar.getInstance();
                        simpleDateFormat = new SimpleDateFormat("hh : mm : ss");
                        time = simpleDateFormat.format(calander.getTime());
                        RemoteViews widgetUi = new RemoteViews(getPackageName(), R.layout.widget);
                        widgetUi.setTextViewText(R.id.idForTimeChange,time);

                            try
                            {
                                ComponentName widgetComponent = new ComponentName(getBaseContext(),AppWidgetObject.class);
                                AppWidgetManager widgetManager = AppWidgetManager.getInstance(getBaseContext());
                                widgetManager.updateAppWidget(widgetComponent, widgetUi);
                                Log.e("Widget", "Ok");
                            }
                            catch (Exception e)
                            {
                                Log.e("widget", "Failed to update widget", e);
                            }



                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            };
            handler.postDelayed(runnable, 0);

        }


    }
}

You can download full code from here, You can modify the code us u like. In like manner feel free to comment your doubt’s below. Does our tutorials help you then help as spread the word, like and share. More details available here.

Creating Interactive Screen Saver with Daydream

DayDreams are interactive screensavers launched when a charging device is idle, or docked in a desk dock. Dreams provide another modality for apps to express themselves, tailored for an exhibition/lean-back experience. So it’s found here and an official example can be found here. DayDream feature was introduced in  Android 4.2,brings this kind of laid-back, whimsical experience to Android phones and tablets that would otherwise be sleeping.However if you haven’t checked it out, you can turn it on in the Settings app, in Display > Daydream touch When to Daydream to enable the feature when charging or docking or both in some cases.

An attract mode for apps

Apps that support Daydream can also take advantage of the full Android UI toolkit in this mode, which means it’s easy to take existing components of your app — including layouts, animations, 3D, and custom views—and remix them for a more ambient presentation.

And since you can use touchscreen input in this mode as well, you can provide a richly interactive experience if you choose.



.Daydream also provides an opportunity for your app to show off a little bit. However you can choose to hide some of your app’s complexity in favor of one or more visually compelling experiences that can entertain from across a room, possibly drawing the user into your full app, like a video game’s attract mode.

The architecture of a Daydream

In fact each Daydream implementation is a subclass of android.service.dreams.DreamService. When you extend DreamService, you’ll have access to a simple Activity-like life-cycle API.

As a matter of fact to be available to the system, your DreamService should be declared in the manifest as follows:

<service
            android:name=".DayDream"
            android:exported="true"
            android:label="@string/my_daydream_name">
            <intent-filter>
                <action android:name="android.service.dreams.DreamService" />
                <category android:name="android.intent.category.DEFAULT" />
            </intent-filter>

            <meta-data
                android:name="android.service.dream"
                android:resource="@xml/dream_info" />
        </service>

Daydream is only available on devices running version 4.2 of Android , which is API Level 17 and above.When targeting api level 21 and above, you must declare the service in your manifest file with the BIND_DREAM_SERVICE permission.



In fact additional information is specified with the <meta-data> element. So additional information for the dream is defined using the <dream> element in a separate XML file. As a result it allows you to point to an XML resource that specifies a settings Activity specific to your Daydream. Currently, the only addtional information you can provide is for a settings activity that allows the user to configure the dream behavior  For example:

res/xml/dream_info.xml

<dream xmlns:android="http://schemas.android.com/apk/res/android"
    android:settingsActivity="com.logicchip.blog_15_daydream.MainActivity" />

This makes a Settings button available alongside your dream’s listing in the system settings, which when pressed opens the specified activity.

In order to specify your dream layout, call setContentView(View), typically during the onAttachedToWindow() callback For example:

DayDream.java

public class DayDream extends DreamService {

    Handler handler;
    Runnable runnable;
    SimpleDateFormat simpleDateFormat;
    Calendar calander;

    @Override
    public void onAttachedToWindow() {
        super.onAttachedToWindow();
        // Hide system UI
        setFullscreen(true);
        // Set the dream layout
        setContentView(R.layout.dream);
    }

    @Override
    public void onDreamingStarted() {
        super.onDreamingStarted();
        TimeChange12();
    }

    public void TimeChange12(){
        handler = new Handler();
        runnable = new Runnable() {
            @Override
            public void run() {
                handler.postDelayed(this, 1000);
                try {
                    calander = Calendar.getInstance();
                    simpleDateFormat = new SimpleDateFormat("hh : mm : ss");
                    TextView txtTime= (TextView)findViewById(R.id.txtTime);
                    txtTime.setText(simpleDateFormat.format(calander.getTime()));

                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        };
        handler.postDelayed(runnable, 0);
    }
}

Consequently layout for dreaming can be whatever we like,  can include animation interactive ui etc.However, be aware that if your screen saver is using too much of the available processing resources, the Android system will stop it from running to allow the device to charge properly.

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="@color/colorAccent">
<LinearLayout
    android:gravity="center"
    android:layout_centerHorizontal="true"
    android:layout_centerVertical="true"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:orientation="vertical">
    <ImageView
        android:layout_width="100dp"
        android:layout_height="100dp"
        android:src="@drawable/logicchip"/>

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="logicchip.com"/>
    <TextView
        android:text="23 : 59 : 59"
        android:textSize="30dp"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:id="@+id/txtTime"/>
</LinearLayout>

</RelativeLayout>

 

Even so “Creating Interactive Screen Saver with Daydream” is explained above you can still download it from here, You can modify the code us u like. In like manner feel free to comment your doubt’s below. Does our tutorials help you then help as spread the word, like and share.