Friday, 24 June 2016

Handling visibility of a view while scrolling Recyclerview

As the name suggests RecyclerView, the views in it are recycled. When you are using a recyclerView and use some small views, for example- say textviews and images etc., in its row then on scrolling the recyclerview the views in the row change. This happens because the views get recycled and reused as onBindViewHolder method in its adapter is called several times as recyclerview needs a view unless it has a new one. So each time you set visibility in child views, other views states are also changed. So whenever you scroll up and down, these views are getting re-drawn with wrong visibility options.
Solution to this problem is very simple.
First take a boolean value to save the clicked value of the item or view as follows:

holder.imgVw.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (isClicked) {
                        holder.txtvw.setVisibility(View.VISIBLE);
                } else {
                        holder.txtvw.setVisibility(View.GONE);
                }
            }
        });
               

Then simply register an Interface in your adapter on the click of particular child view as follows:

holder.imgVw.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                yourListener.onSelectingView(position, holder.txtvw.getId);
                if (isClicked) {
                        holder.txtvw.setVisibility(View.VISIBLE);
                } else {
                        holder.txtvw.setVisibility(View.GONE);
                }
            }
        });

Now in your activity, in the implemented methods of your listener do the following:

@Override
    public void onSelectingView(int position, String id) {
        adapter.notifyDataSetChanged();
        mRecyclerView.invalidate();
    }

That's all.. your view will not change its visibility on scrolling of the recyclerview.

Happy coding and remember "Code to make it better..!!"



Friday, 10 June 2016

Rounded Image with Glide

Glide is a fast and efficient open source image loading framework for Android that wraps memory and disk caching, and resource pooling into a simple and easy to use interface.
Glide supports fetching, decoding, and displaying video stills, images, and animated GIFs.
Glide includes a flexible API that allows developers to plug in to almost any network stack. By default Glide uses a custom HttpUrlConnection based stack, but also includes utility libraries plug in to Google's Volley project or Square's OkHttp library instead.
Glide's primary focus is on making scrolling any kind of a list of images as smooth and fast as possible, but Glide is also effective for almost any case where you need to fetch, resize, and display a remote image.

Download
You can download a jar from GitHub's releases page.
Or use Gradle:

dependencies {
  compile 'com.github.bumptech.glide:glide:3.7.0'
  compile 'com.android.support:support-v4:19.1.0'
}

Basic
The basic way to load a remote image into an ImageView with Glide is quite simple:

Glide.with(context)  //you can pass either context or activity or fragment
    .load("YOUR_IMAGE_URL") //or fragmentactivity,Glide accepts everything
    .into(YOUR_IMAGEVIEW);

For Circular ImageView, you can use RoundedBitmapDrawable with Glide as follows:
(No Custom ImageView is required for this)

 Glide.with(context).load(YOUR_IMAGE_URL).asBitmap().centerCrop().into(new BitmapImageViewTarget(YOUR_IMAGEVIEW) {
        @Override
        protected void setResource(Bitmap resource) {
            RoundedBitmapDrawable circularBitmapDrawable =
                    RoundedBitmapDrawableFactory.create(context.getResources(), resource);
            circularBitmapDrawable.setCircular(true);
            YOUR_IMAGEVIEW.setImageDrawable(circularBitmapDrawable);
        }
    });
This will make your imageview look circular.

That's all.. and always code to make it better.. :)


Saturday, 4 June 2016

Card View (Android)

Hi guys, this blog of mine will give you an example of a new user interface widget introduced in Android support library (v7:21.0.+) that is: CardView that helps in building rich Android apps.

CardView widget, is an extension of existing FrameLayout class. This helps to wrap other UI elements as Google style cards. CardView widgets can have shadows and rounded corners.
Following the blog will show you how to use the CardView in your application.

Add CardView Support Library
Android SDK doesn’t includes the CardView class, and hence for using CardView in your project you first need to add the card view support library to your project. Android Studio users can add the following gradle dependency in your build.graddle file to add CardView to project.

dependencies {
       compile 'com.android.support:cardview-v7:21.0.+'
}

Declare CardView Layout
Now that we have added the build dependencies to project, let us go ahead to declare the CardView layout. You can define the layout of your cardView according to your needs. For example, I am adding a textview and an ImageView in my layout.

<?xml version="1.0" encoding="utf-8"?>
<android.support.v7.widget.CardView xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/card_view"
    android:layout_width="match_parent"
    android:layout_height="240dp"
    android:layout_margin="16dp">

<RelativeLayout 
    android:layout_width="match_parent"
    android:layout_height="match_parent">

<ImageView
                android:id="@+id/imgvw"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_alignParentTop="true"
                android:layout_centerHorizontal="true"
                android:layout_margin="16dp"
                android:src="@drawable/sample_image" />

             <TextView
                android:id="@+id/txtvw"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_centerInParent="true"
                android:text="CardView Example" />

</RelativeLayout>
</android.support.v7.widget.CardView>


Customize CardView Appearance
The CardView layout declaration is pretty straight forward. CardView widget allows you to control the background color, shadow, corner radius etc. For using the custom attributes in XML, you need to add the following namespace declaration to your parent layout and then add your other attributes to customize your cardview style as follows.

<android.support.v7.widget.CardView 
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    xmlns:cardView="http://schemas.android.com/apk/res-auto"
    android:id="@+id/card_view"
    android:layout_width="match_parent"
    android:layout_height="240dp"
    android:layout_margin="16dp"
   app:cardCornerRadius="8dp"
    app:cardBackgroundColor="#fff"
    app:cardElevation="4dp" ... >

<-- Define your layout here -->

</android.support.v7.widget.CardView>

That's it...Enjoy!! and always Code to make it better..!!



Saturday, 28 May 2016

Toolbar title in center

If you want your title text to be in center of your toolbar, you have two simple ways to do it.
First approach:-
Remember that the Toolbar is just a ViewGroup like others. So you can simply add Views into it.
In this case, you need a TextView inside a Toolbar at center position. So, simply define a layout for your toolbar containing a textview like this:

app_bar.xml

<android.support.v7.widget.Toolbar
    android:id="@+id/toolbar"
    android:layout_height="wrap_content"
    android:layout_width="match_parent">

    <TextView
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:text="Some Fancy Title"
        android:gravity = "center"
        android:id="@+id/toolbar_title" />

</android.support.v7.widget.Toolbar>

Then just include this layout in activity's XML file like:

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

Then, in your Java file(Activity.java) access your toolbar and textview as follows:

Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);
        getSupportActionBar().setDisplayShowTitleEnabled(false);
TextView mTitle = (TextView) toolbar.findViewById(R.id.toolbar_title);

Since the textview gravity is already set to "center", it will display the text in center of the toolbar.


Second approach:-
You can just use the below method and pass your toolbar variable as parameter to it to make your title centered.

public static void centerToolbarTitle(final Toolbar toolbar) {
        final CharSequence title = toolbar.getTitle();
        final ArrayList<View> outViews = new ArrayList<>(1);
        toolbar.findViewsWithText(outViews, title, View.FIND_VIEWS_WITH_TEXT);
        if (!outViews.isEmpty()) {
            final TextView titleView = (TextView) outViews.get(0);
            titleView.setGravity(Gravity.CENTER_HORIZONTAL);
            final Toolbar.LayoutParams layoutParams = (Toolbar.LayoutParams) titleView.getLayoutParams();
            layoutParams.width = ViewGroup.LayoutParams.MATCH_PARENT;
            layoutParams.setMargins(0,0,60,0);
            toolbar.requestLayout();
        }
    }

Thas'it..!!! Enjoy!!


Friday, 20 May 2016

Disable background touch events on showing ProgressBar

When showing the progress bar loader while performing some operation, to disable your background controls or in other words if I say that, showing a progress bar spinner only with the properties of a Progress Dialog, here is the solution, how:-

In order to use Progress Bar, define it in the xml like this.

<ProgressBar                                                                          
   android:id="@+id/progressBar1"                                       
   style="?android:attr/progressBarStyleLarge"                     
   android:layout_width="wrap_content"                               
   android:layout_height="wrap_content"                              
   android:layout_centerHorizontal="true" />                        

After defining it in xml, get its reference in java file as follows−

private ProgressBar spinner;                                                  
spinner = (ProgressBar)findViewById(R.id.progressBar1); 


Now use the below method to show the spinner loader and disable user touch events on background like in the case of a progress dialog.

 void showLoading(){                                                                                                              
        spinner.setVisibility(View.VISIBLE);                                                                             
        getWindow().setFlags(WindowManager.LayoutParams.FLAG_NOT_TOUCHABLE,
                WindowManager.LayoutParams.FLAG_NOT_TOUCHABLE);                           
    }                                                                                                                                           

In order to dismiss the spinner loader and enable the backgroung touch events, use the below method:-

 void dismissLoading(){                                                                                                               
        spinner.setVisibility(View.INVISIBLE);                                                                             
        getWindow().clearFlags(WindowManager.LayoutParams.FLAG_NOT_TOUCHABLE);
    }                                                                                                                                                


Also like in the case of a Progress Dialog, if you want to add the feature of semi-transparent greyed display while your loading spinner is visible, you need to set the background of the linear layout to #80000000 and its visibilty to Gone in your xml file . Then programmatically set its visibility to Visible when required.

Enjoy..!! and Code to make it better..!!!



Monday, 16 May 2016

Difference between popBackStack() and replace() in Fragments


Using Fragments in your application is a very good practise that makes the application more responsive and transitive in the sense that it looks a bit fast. But sometimes it becomes a problem to manage these fragments. Now to differentiate the two main functions in fragments i.e popBackStack() and replace(), lets take two fragments, Fragment (A) and Fragment (B).

Now the replace() performs two things:-

  • Remove currently added fragment (A) from the container (C) you indicated.
  • Add new fragment (B) to the same container.

These 2 operations are what is saved as a Backstack record / transaction.
Note that fragment A remains in created state, but its view is destroyed.

Now popBackStack() reverses your last transaction that you've performed through replace().
In this case that would be 2 steps:

  • Remove fragment (B) from container (C).
  • Add fragment (A) to container C.

After this, fragment B becomes detached, and if you did not keep references to it, it will be garbage collected.

Now it is important to understand that you don't actually add Fragments to Backstack, you add FragmentTransactions. So when you think that you are doing "replace with Fragment B, and adding Fragment A to the back stack", then you actually add this whole operation to backstack - that is- remove A and add B.

Then, next step is popping of the transaction that contains this replacement. So you're not popping FragmentA, you're reversing the above transaction "remove A, add B", which when reversed is "remove B, add A".

So after this - there's no fragment (B) that the FragmentManager is aware of, so when you add it by replacing A with B at the above step, B needs to go through its early lifecycle methods - onAttach() and onCreate().

That's all, enjoy.!! and always code to make it better..!!

Friday, 6 May 2016

Eclipse Shortcuts for Android Studio Users

Many of you might be very familiar with working on eclipse and more comfortable with the shortcuts used in it. And now after swithcing to Android Studio you must be missing those shortcuts.
So here is the way to get your favourite eclipse shortcuts in Android Studio.
Go to:-
File -> Settings -> Keymap -> <Choose Eclipse from Keymaps dropdown>


To know more about shortcuts, go to this Link.

Other Programming shortcuts in Android Studio are as follows:
Reformat code -------------------------------------------CTRL + ALT + L
Optimize imports ---------------------------------------CTRL + ALT + O
Code Completion ---------------------------------------CTRL + SPACE
Issue quick fix -------------------------------------------ALT + ENTER
Surround code block -----------------------------------CTRL + ALT + T
Rename and Refractor ---------------------------------Shift + F6
Line Comment or Uncomment -----------------------CTRL + /
Block Comment or Uncomment ---------------------CTRL + SHIFT + /
Go to previous/next method --------------------------ALT + UP/DOWN
Show parameters for method ------------------------CTRL + P
Quick documentation lookup ------------------------CTRL + Q
Delete a line --------------------------------------------CTRL + Y
View declaration in layout ---------------------------CTRL + B

Happy coding & code to make it better..!!