Sunday, 22 January 2017

Animate a view with TranslateAnimation in android

TranslateAnimation class inherited from Animation class, is basically an animation that controls the position of an object.
The public constructors are:

-    TranslateAnimation(Context context, AttributeSet attrs)
     Constructor used when a TranslateAnimation is loaded from a resource.

-   TranslateAnimation(float fromXDelta, float toXDelta, float fromYDelta, float toYDelta)
    Constructor to use when building a TranslateAnimation from code

-   TranslateAnimation(int fromXType, float fromXValue, int toXType, float toXValue, int                         fromYType, float fromYValue, int toYType, float toYValue)
    Constructor to use when building a TranslateAnimation from code

In this post I will show you how to move your view from one point to another on your screen with the help of TranslateAnimation class.
There are basically two ways to use this class which are as follows:

1. You can simple call the constructor, mentioned above to apply your transition as follows:

                        TranslateAnimation animation = new TranslateAnimation(0, 0, 100, 0);  
                        animation.setDuration(1000);                                                                     
                        yourImageView.startAnimation(animation);                                              

(called constructor:
TranslateAnimation(float fromXDelta, float toXDelta, float fromYDelta, float toYDelta)
fromXDelta       float: Change in X coordinate to apply at the start of the animation
toXDelta               float: Change in X coordinate to apply at the end of the animation
fromYDelta       float: Change in Y coordinate to apply at the start of the animation
toYDelta               float: Change in Y coordinate to apply at the end of the animation)

2. You can use the following method: (Recommended)


public void moveViewToCenter( View view ) {                                                       
                                                                                                                                    
    RelativeLayout root = (RelativeLayout) findViewById( R.id.rootLayout );        
    DisplayMetrics dm = new DisplayMetrics();                                                       
    this.getWindowManager().getDefaultDisplay().getMetrics( dm );                      
    int statusBarOffset = dm.heightPixels - root.getMeasuredHeight();                   
                                                                                                                                  
    int originalPos[] = new int[2];                                                                              
    view.getLocationOnScreen( originalPos );                                                             
                                                                                                                                       
    int xDest = dm.widthPixels/2;                                                                                  
    xDest -= (view.getMeasuredWidth()/2);                                                                     
    int yDest = dm.heightPixels/2 - (view.getMeasuredHeight()/2) - statusBarOffset;   
                                                                                                                                              
    TranslateAnimation anim = new TranslateAnimation( 0, xDest - originalPos[0] , 0, yDest - originalPos[1] );                                                                                                        
    anim.setDuration(1000);                                                                                      
    anim.setFillAfter( true );                                                                                      
    view.startAnimation(anim);                                                                                  
                                                                                                                                   
}                                                                                                                               

While using the above method just place your view(to be moved) in a full screen layout. By doing so you won't have to worry about overlapping and clipping other views.
The method moveViewToCenter gets the View's absolute coordinates and calculates how much distance it has to move from its current position to reach the center of the screen. The statusBarOffset variable measures the status bar height.

This is how you can use TranslateAnimation and move your views.
That's all.


Thursday, 12 January 2017

Handling Screen Configuration changes

Handling the screen orientation changes on your android device is sometimes the most irritating and frustrating part in your development cycle. So in this post i will try to remove that frustration and will tell you what exactly happens during the screen orientation process.

When we rotate our device and the screen changes orientation, android system usually destroys our application’s existing activities or fragments and restarts the running activity/fragment(onDestroy() is called, followed by onCreate()). Android System do this so that our application can reload all the resources based on the new configuration.

To work around this thing, Android gives us the option to save our app’s state before destroying all of our activities and fragments, and also to restore that state when recreating them. Thus, proper handling of orientation changes centers around saving this state and also avoiding memory leaks.
So to properly handle a restart, it is important that our activity restores its previous state through the normal activity lifecycle, in which Android calls onSaveInstanceState() before it destroys our activity so that we can save our data about the application state. We can then restore the state during onCreate() or onRestoreInstanceState().

While it may seem a bit hectic to implement this all, handling screen orientation changes properly provides you with several benefits as well:
- You will be able to easily use alternate layouts in portrait and landscape orientations, and you will be able to handle many exceptional states such as low memory situations and interruptions from incoming phone calls without any extra code.

Implementation:
The first thing that you should do is set the android:configChanges flag on your Activity in AndroidManifest.xml as shown below:

<activity
    android:name=".YourActivity"
    android:label="@string/activity_one"
    android:configChanges="orientation|screenSize|keyboardHidden" />

This flag signals to the Android platform that you are going to manually handle your screen orientation, screenSize and keyboard appearance/disappearance changes for this Activity.

Now, when one of these above mentioned configurations change, YourActivity does not restart. Instead, the YourActivity receives a call to onConfigurationChanged() method. This method has a Configuration object that specifies the new device configuration. By reading fields in the Configuration, you can determine the new configuration and make appropriate changes by updating the resources used in your interface. At the time this method is called, your activity's Resources object is updated to return resources based on the new configuration, so you can easily reset elements of your UI without the system restarting your activity.

@Override
public void onConfigurationChanged(Configuration newConfig) {
    super.onConfigurationChanged(newConfig);

    // Checks the orientation of the screen
    if (newConfig.orientation == Configuration.ORIENTATION_LANDSCAPE) {
        // Do your stuff in landscape mode
        Toast.makeText(this, "landscape", Toast.LENGTH_SHORT).show();
    } else if (newConfig.orientation == Configuration.ORIENTATION_PORTRAIT){
       // Do your stuff in portrait mode 
       Toast.makeText(this, "portrait", Toast.LENGTH_SHORT).show();
    }
}

The Configuration object represents all of the current configurations, not just the ones that have changed.
If you don't need to update your application based on these configuration changes, you can instead not implement onConfigurationChanged(). In this case, all of the resources used before the configuration change are still used and you've only avoided the restart of your activity.

Note: When you declare your activity to handle a configuration change, you are responsible for resetting any elements for which you provide alternatives. If you declare your activity to handle the orientation change and have images that should change between landscape and portrait, you must re-assign each resource to each element during onConfigurationChanged().

That's all.
Share and comment if any issues.
References: https://developer.android.com/guide/topics/resources/runtime-changes.html

Thursday, 5 January 2017

Android: DateTimePicker

This post is regarding how to use/implement DateTimePicker in your android app.
DateTimePicker in android is a UI control which is very useful in your app and gives a nice feel to your app if your app contains some date or time related usage.

https://developer.android.com recommend that you use DialogFragment to host each time or date picker. The DialogFragment manages the dialog lifecycle for you and allows you to display the pickers in different layout configurations, such as in a basic dialog on your handsets or as an embedded part of the layout on large screens.
So let's start with the implementation of this UI control which is as simple as follows:

-Create a Time Picker
Create a static class to show your TimePicker by extending DialogFragment as follows:

public static class TimePickerFragment extends DialogFragment
                            implements TimePickerDialog.OnTimeSetListener {

    @Override
    public Dialog onCreateDialog(Bundle savedInstanceState) {
        // Use the current time as the default values for the picker
        final Calendar c = Calendar.getInstance();
        int hour = c.get(Calendar.HOUR_OF_DAY);
        int minute = c.get(Calendar.MINUTE);

        // Create a new instance of TimePickerDialog and return it
        return new TimePickerDialog(getActivity(), this, hour, minute,
                DateFormat.is24HourFormat(getActivity()));
    }

    public void onTimeSet(TimePicker view, int hour, int minute) {
        // Do something with the time chosen by the user
        // Your selected time will be (hour:minute)          
    }
}

-Show the time picker
Now add a button to your layout xml file as follows:

<Button
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="@string/pick_time"
    android:onClick="showTimePickerDialog" />

-When you will click this button, the system will call the following method:

public void showTimePickerDialog(View v) {
    DialogFragment newFragment = new TimePickerFragment();
    newFragment.show(getSupportFragmentManager(), "timePicker");
}

That's all. After this you will be able to see a TimePicker from where you can select your time. After selecting the time you can get your selected time (callback) in the onTimeSet() method of your TimePicker class that you just created above.    

-Create a Date Picker
Create a static class to show your DatePicker by extending DialogFragment as follows:

public static class DatePickerFragment extends DialogFragment
                            implements DatePickerDialog.OnDateSetListener {

    @Override
    public Dialog onCreateDialog(Bundle savedInstanceState) {
        // Use the current date as the default date in the picker
        final Calendar c = Calendar.getInstance();
        int year = c.get(Calendar.YEAR);
        int month = c.get(Calendar.MONTH);
        int day = c.get(Calendar.DAY_OF_MONTH);

        // Create a new instance of DatePickerDialog and return it
        return new DatePickerDialog(getActivity(), this, year, month, day);
    }

    public void onDateSet(DatePicker view, int year, int month, int day) {
        // Do something with the date chosen by the user
        // Your selected date will be (day/month/year)    
    }
}

-Show the date picker
Now add another button to your layout xml file as follows:

<Button
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="@string/pick_date"
    android:onClick="showDatePickerDialog" />

-When you will click this button, the system will call the following method:

public void showDatePickerDialog(View v) {
    DialogFragment newFragment = new DatePickerFragment();
    newFragment.show(getSupportFragmentManager(), "datePicker");
}


That's all. After this you will be able to see a DatePicker from where you can select your date. After selecting the date you can get your selected date (callback) in the onDateSet() method of your DatePicker class that you just created above.

Share and comment if any issues.





Monday, 26 December 2016

Android: Creating a Custom Navigation Drawer

The navigation drawer is a panel that displays the app’s main navigation options on the left edge of the screen. It is hidden most of the time, but is revealed when the user swipes a finger from the left edge of the screen or, while at the top level of the app, the user touches the app icon in the action bar.
This post describes how to implement a Navigation Drawer using DrawerLayout a few simple steps.

1. Create a Drawer Layout:
    Create a file under res/layout/ folder named as activity_home.xml:

 <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/top_parent"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:fitsSystemWindows="true">

    <include
        android:id="@+id/toolbar"
        layout="@layout/layout_toolbar" />

    <android.support.v4.widget.DrawerLayout
        android:id="@+id/drawer_layout"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_below="@+id/toolbar">

        <!-- The main content view -->
        <FrameLayout
            android:id="@+id/content_frame"
            android:layout_width="match_parent"
            android:layout_height="match_parent">

        </FrameLayout>

        <!-- The navigation drawer -->
        <ListView
            android:id="@+id/left_drawer"
            android:layout_width="240dp"
            android:layout_height="match_parent"
            android:layout_gravity="start"
            android:background="@color/colorPrimaryDark"
            android:choiceMode="singleChoice"
            android:divider="@android:color/white"
            android:dividerHeight="0.5dp" />

    </android.support.v4.widget.DrawerLayout>
</RelativeLayout>

2. Create a Toolbar layout for your app's actionbar:
    Create a file under res/layout/ folder named as layout_toolbar.xml to show the home button animation as suggested in Material design:

<?xml version="1.0" encoding="utf-8"?>
<android.support.v7.widget.Toolbar xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/toolbar"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:background="?attr/colorPrimaryDark">

    <TextView
        android:id="@+id/toolbar_title"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Title"
        android:textAlignment="center"
        android:textAppearance="@android:style/TextAppearance.Material.Widget.Toolbar.Title"
        android:textColor="@android:color/white" />
</android.support.v7.widget.Toolbar>

3. Initialize your drawer list:
    Create a class named as HomeActivity.java and use the following code snippet:

public class HomeActivity extends AppCompatActivity {
    private DrawerLayout mDrawerLayout;
    private ListView mDrawerList;
    private ActionBarDrawerToggle mDrawerToggle;
    ArrayList<NavigationDrawerItemPOJO> pojoArrayList;
    Toolbar toolbar;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_home);
     
        mDrawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
        mDrawerList = (ListView) findViewById(R.id.left_drawer);

        pojoArrayList = new ArrayList<>();
        NavigationDrawerItemPOJO nav = new NavigationDrawerItemPOJO();
        nav.setIcon(R.mipmap.ic_launcher);
        nav.setName("Name 1");
        pojoArrayList.add(nav);
       
        mDrawerList.setAdapter(new NavigationDrawerAdapter(this, R.layout.item_navigation_drawer, pojoArrayList));

        // Set the list's click listener
        mDrawerList.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int position, long l) {
                Toast.makeText(getApplicationContext(), "Item clicked: " + position, Toast.LENGTH_SHORT).show();
                mDrawerLayout.closeDrawer(mDrawerList);
            }
        });
       .. .. ..
    }
}


4. Setup your drawer layout:

public class HomeActivity extends AppCompatActivity {
    private DrawerLayout mDrawerLayout;
    private ListView mDrawerList;
    private ActionBarDrawerToggle mDrawerToggle;
    ArrayList<NavigationDrawerItemPOJO> pojoArrayList;
    Toolbar toolbar;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_home);
        initToolbar();

.........

        mDrawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
        mDrawerToggle = new ActionBarDrawerToggle(this, mDrawerLayout, toolbar, R.string.drawer_open, R.string.drawer_close) {

            /** Called when a drawer has settled in a completely closed state. */
            public void onDrawerClosed(View view) {
                super.onDrawerClosed(view);
                invalidateOptionsMenu(); // creates call to onPrepareOptionsMenu()
                syncState();
            }

            /** Called when a drawer has settled in a completely open state. */
            public void onDrawerOpened(View drawerView) {
                super.onDrawerOpened(drawerView);
                invalidateOptionsMenu(); // creates call to onPrepareOptionsMenu()
                syncState();
            }
        };

        // Set the drawer toggle as the DrawerListener
        mDrawerLayout.addDrawerListener(mDrawerToggle);
        mDrawerToggle.syncState();
    }

    //Set the custom toolbar
    public void initToolbar() {
        toolbar = (Toolbar) findViewById(R.id.toolbar);
        if (toolbar != null) {
            setSupportActionBar(toolbar);
        }
        getSupportActionBar().setDisplayHomeAsUpEnabled(true);
        getSupportActionBar().setHomeButtonEnabled(true);
        getSupportActionBar().setDisplayShowTitleEnabled(false);
        TextView txtvw = (TextView) findViewById(R.id.toolbar_title);
        txtvw.setText("Nishant");
    }
.....
}

5. Create your drawer adapter and drawer item POJO:

public class NavigationDrawerAdapter extends ArrayAdapter<NavigationDrawerItemPOJO> {
        private final Context context;
        private final int layoutResourceId;
        private ArrayList<NavigationDrawerItemPOJO> arrayList;

        public NavigationDrawerAdapter(Context context, int layoutResourceId,
                                                     ArrayList<NavigationDrawerItemPOJO> arrayList) {
            super(context, layoutResourceId, arrayList);
            this.context = context;
            this.layoutResourceId = layoutResourceId;
            this.arrayList = arrayList;
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            LayoutInflater inflater = ((Activity) context).getLayoutInflater();
            View v = inflater.inflate(layoutResourceId, parent, false);
            ImageView imageView = (ImageView) v.findViewById(R.id.navDrawerImageView);
            TextView textView = (TextView) v.findViewById(R.id.navDrawerTextView);
            NavigationDrawerItemPOJO choice = arrayList.get(position);
            imageView.setImageResource(choice.getIcon());
            textView.setText(choice.getName());
            return v;
        }
    }

    public class NavigationDrawerItemPOJO {
        public int getIcon() {
            return icon;
        }

        public void setIcon(int icon) {
            this.icon = icon;
        }

        public String getName() {
            return name;
        }

        public void setName(String name) {
            this.name = name;
        }

        public int icon;
        public String name;

        public NavigationDrawerItemPOJO() {
        }
   }

That's all..!!
After this your home activity will look something like this:

HomeActivity.java
 
public class HomeActivity extends AppCompatActivity {
    private DrawerLayout mDrawerLayout;
    private ListView mDrawerList;
    private ActionBarDrawerToggle mDrawerToggle;
    ArrayList<NavigationDrawerItemPOJO> pojoArrayList;
    Toolbar toolbar;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_home);
        initToolbar();
        mDrawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
        mDrawerList = (ListView) findViewById(R.id.left_drawer);

        pojoArrayList = new ArrayList<>();
        NavigationDrawerItemPOJO nav = new NavigationDrawerItemPOJO();
        nav.setIcon(R.mipmap.ic_launcher);
        nav.setName("Name 1");
        pojoArrayList.add(nav);
        NavigationDrawerItemPOJO nav1 = new NavigationDrawerItemPOJO();
        nav1.setIcon(R.mipmap.ic_launcher);
        nav1.setName("Name 2");
        pojoArrayList.add(nav1);
        mDrawerList.setAdapter(new NavigationDrawerAdapter(this, R.layout.item_navigation_drawer, pojoArrayList));

        // Set the list's click listener
        mDrawerList.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int position, long l) {
                Toast.makeText(getApplicationContext(), "Item clicked: " + position, Toast.LENGTH_SHORT).show();
                mDrawerLayout.closeDrawer(mDrawerList);
            }
        });

        mDrawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
        mDrawerToggle = new ActionBarDrawerToggle(this, mDrawerLayout, toolbar, R.string.drawer_open, R.string.drawer_close) {

            /** Called when a drawer has settled in a completely closed state. */
            public void onDrawerClosed(View view) {
                super.onDrawerClosed(view);
                invalidateOptionsMenu(); // creates call to onPrepareOptionsMenu()
                syncState();
            }

            /** Called when a drawer has settled in a completely open state. */
            public void onDrawerOpened(View drawerView) {
                super.onDrawerOpened(drawerView);
                invalidateOptionsMenu(); // creates call to onPrepareOptionsMenu()
                syncState();
            }
        };

        // Set the drawer toggle as the DrawerListener
        mDrawerLayout.addDrawerListener(mDrawerToggle);
        mDrawerToggle.syncState();
    }

    //Set the custom toolbar
    public void initToolbar() {
        toolbar = (Toolbar) findViewById(R.id.toolbar);
        if (toolbar != null) {
            setSupportActionBar(toolbar);
        }
        getSupportActionBar().setDisplayHomeAsUpEnabled(true);
        getSupportActionBar().setHomeButtonEnabled(true);
        getSupportActionBar().setDisplayShowTitleEnabled(false);
        TextView txtvw = (TextView) findViewById(R.id.toolbar_title);
        txtvw.setText("Nishant");
    }

    public class NavigationDrawerAdapter extends ArrayAdapter<NavigationDrawerItemPOJO> {
        private final Context context;
        private final int layoutResourceId;
        private ArrayList<NavigationDrawerItemPOJO> arrayList;

        public NavigationDrawerAdapter(Context context, int layoutResourceId, ArrayList<NavigationDrawerItemPOJO> arrayList) {
            super(context, layoutResourceId, arrayList);
            this.context = context;
            this.layoutResourceId = layoutResourceId;
            this.arrayList = arrayList;
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            LayoutInflater inflater = ((Activity) context).getLayoutInflater();
            View v = inflater.inflate(layoutResourceId, parent, false);
            ImageView imageView = (ImageView) v.findViewById(R.id.navDrawerImageView);
            TextView textView = (TextView) v.findViewById(R.id.navDrawerTextView);
            NavigationDrawerItemPOJO choice = arrayList.get(position);
            imageView.setImageResource(choice.getIcon());
            textView.setText(choice.getName());
            return v;
        }
    }

    public class NavigationDrawerItemPOJO {
        public int getIcon() {
            return icon;
        }

        public void setIcon(int icon) {
            this.icon = icon;
        }

        public String getName() {
            return name;
        }

        public void setName(String name) {
            this.name = name;
        }

        public int icon;
        public String name;

        public NavigationDrawerItemPOJO() {
        }
    }
}


Run it and enjoy your app with a drawer that has material design drawer animation.
In this post your drawer will slide below the actionBar, just to show the animation. You can have it over the actionBar as well.

Share, Comment and Reply if any issues.


Friday, 16 December 2016

Android: Implement "Press BACK again to exit"

You might have noticed a pattern in many android applications these days in which on pressing the back button to exit the application it gives you a message which says "Please press BACK again to exit" .
This post is regarding implementing this feature in your android app.
To implement this, you just need to do the following things:

1. In your activity in which you want to implement this feature, add a variable as follows:
                         
                                 private boolean isBackPressedOnce = false;  

2. Now add the following code in the onBackPressed() method of your activity as follows:

    @Override
    public void onBackPressed() {
            if (isBackPressedOnce) {
                super.onBackPressed();
                return; // exit the appliactaion
            }

            this.isBackPressedOnce = true;
            Toast.makeText(this, "Please press BACK again to exit", Toast.LENGTH_SHORT).show();

            new Handler().postDelayed(new Runnable() {
                @Override
                public void run() {
                    isBackPressedOnce = false;
                    // Runnable to change the value of variable isBackPressedOnce to true after 2 
                    // seconds if you take more than 2 seconds of time in pressing the back button again.
                }
            }, 2000);

    }

That's all. Now on pressing the back button in your app it will show you the message "Please press BACK again to exit".

Share & comment if any issues.


Sunday, 11 December 2016

Android Animations: Expand & Collapse

In reference to my previous post here, this post is regarding some other styles of animation that you can use in your app to make it look more subtle.
As you know Animations in android can add subtle visual cues that notify users about what's going on in your app and improve their mental model of your app's interface. Animations are especially useful when the screen changes state, such as when content loads or new actions become available. Animations can also add a polished look to your app, which gives your app a higher quality feel.

So lets get started now: This tutorial shows you simple way to add Expand & Collapse style animation in your app in just a few steps.
The Expand animation is somewhat like unfolding a view step by step or you can say opening a view from 0 to 100 slowly.
So to add the expand animation in your app just add the following method in your code:

public static void expandAnimation(final View v) {
        v.measure(WindowManager.LayoutParams.MATCH_PARENT, WindowManager.LayoutParams.WRAP_CONTENT);
        final int targetHeight = v.getMeasuredHeight();
        // Older versions of android (pre API 21) cancel animations for views with a height of 0.
        v.getLayoutParams().height = 1;
        v.setVisibility(View.VISIBLE);
        Animation a = new Animation() {
            @Override
            protected void applyTransformation(float interpolatedTime, Transformation t) {
                v.getLayoutParams().height = interpolatedTime == 1
                        ? WindowManager.LayoutParams.WRAP_CONTENT
                        : (int) (targetHeight * interpolatedTime);
                v.requestLayout();
            }
            @Override
            public boolean willChangeBounds() {
                return true;
            }
        };
        // 1dp/ms
        a.setDuration(300);
        v.startAnimation(a);
    }
          

Now to set this animation on any view, just call this method and pass that view which you want to expand, as the parameter to this method as follows:

                    expandAnimation(findViewById(R.id.myview));       

Now after expanding the view you also need to close it or you can say you'll need to collapse it.
Don't worry, closing it is also as simple as expanding it.
Just add the following method in your code to collapse your view.    

public static void collapseAnimation(final View v) {
        final int initialHeight = v.getMeasuredHeight();
        Animation a = new Animation() {
            @Override
            protected void applyTransformation(float interpolatedTime, Transformation t) {
                if (interpolatedTime == 1) {
                    v.setVisibility(View.GONE);
                } else {
                    v.getLayoutParams().height = initialHeight - (int) (initialHeight * interpolatedTime);
                    v.requestLayout();
                }
            }
            @Override
            public boolean willChangeBounds() {
                return true;
            }
        };
        // 1dp/ms
        a.setDuration(300);
        v.startAnimation(a);
    }
        

Now to set this collapse animation on any view, just call this method as you called the method to expand it and pass that view which you want to collapse, as the parameter to this method as follows:

                       collapseAnimation(findViewById(R.id.myview));    

That's all. Use it and have fun.
Comment if any issues and share.



Sunday, 27 November 2016

Fix Error: Configuration with name 'default' not found in android-studio

While importing or cloning a code from any version control system you might sometimes get an error showing you as "Error: Configuration with name 'default' not found". This error generally occurs due to following reasons:
1. When a module doens't have the build.gradle file,
2. You're trying to use a project that doesn't have a "build.gradle" file.

Essentially the build.gradle file for each submodule needs to have the information on how to build itself and any custom gradle command definitions.
So, you need to make sure that each submodule in your project has its own build.gradle file.
The name 'default' happens because your project level build.gradle is trying to build a project that doesn't know how to build itself, thus it is given the name 'default.'

Fix 1:
- If you are cloning a project from a version control system, then make a new clone of your project:

                                       git clone <LINK_TO_YOUR_PROJECT>  

and then issue the git submodule command:

                                       git submodule update --init --recursive  
and after this check whether your external folders are being populated with required folders and files.

Fix 2:
- After importing your project, run the following to commands:
                                       git submodule init  
                                       git submodule update  

Fix 3:
Add you library projects in your app level build.gradle file as follows:

               compile fileTree(dir: 'libs', include: ['*.jar'])              
               compile 'com.android.support:appcompat-v7:21.0.3' 
               compile project(":libs:<Your project name>")      

For more information on gradle visit: http://tools.android.com/tech-docs/new-build-system/user-guide


Thanks and reply if any issues.