Sunday, November 29, 2020

How to apply slide animation between two activities in Android

 I want to achieve a sliding effect from left to right when I move from one activity to another. For that I am using the following code, but I am not getting any results. Please correct me.


How to apply slide animation between two activities in Android

You can overwrite your default activity animation and it perform better than overridePendingTransition. I use this solution that work for every android version. Just copy paste 4 files and add a 4 lines style as below: Create a "CustomActivityAnimation" and add this to your base Theme by "windowAnimationStyle".

<!-- Base application theme. -->

<style name="AppTheme" parent="Theme.AppCompat.Light.NoActionBar">

    <!-- Customize your theme here. -->

    <item name="colorPrimary">@color/colorPrimary</item>

    <item name="colorPrimaryDark">@color/colorPrimaryDark</item>

    <item name="colorAccent">@color/colorPrimary</item>

    <item name="android:windowAnimationStyle">@style/CustomActivityAnimation</item>

</style>

<style name="CustomActivityAnimation" parent="@android:style/Animation.Activity">

    <item name="android:activityOpenEnterAnimation">@anim/slide_in_right</item>

    <item name="android:activityOpenExitAnimation">@anim/slide_out_left</item>

    <item name="android:activityCloseEnterAnimation">@anim/slide_in_left</item>

    <item name="android:activityCloseExitAnimation">@anim/slide_out_right</item>

</style>

slide_in_right.xml

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

<set xmlns:android="http://schemas.android.com/apk/res/android">

    <translate android:fromXDelta="100%p" android:toXDelta="0"

        android:duration="@android:integer/config_mediumAnimTime"/>

</set>

slide_out_left.xml

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

<set xmlns:android="http://schemas.android.com/apk/res/android">

    <translate android:fromXDelta="0" android:toXDelta="-100%p"

        android:duration="@android:integer/config_mediumAnimTime"/>

</set>

slide_in_left.xml

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

<set xmlns:android="http://schemas.android.com/apk/res/android">

    <translate android:fromXDelta="-100%p" android:toXDelta="0"

        android:duration="@android:integer/config_mediumAnimTime"/>

</set>

slide_out_right.xml

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

<set xmlns:android="http://schemas.android.com/apk/res/android">

    <translate android:fromXDelta="0" android:toXDelta="100%p"

        android:duration="@android:integer/config_mediumAnimTime"/>

</set>

 

Saturday, November 28, 2020

Android RecyclerView adding Search Filter

 Today, in this article we are going to learn how to add search filter functionality to RecyclerView. Adding search is very simple task, we’ll use Toolbar’s search widget to input the search query. To demonstrate I am taking an example of contacts list and search for a contact by name or phone number.

Android RecyclerView adding Search Filter

RecyclerView Search Filter – getFilter()

Android provides Filterable class to filter the data by a filter (condition). Usually the getFilter() method has to be overridden in the adapter class in which the filter condition is provided to search through a list. Below is an example of getFilter() method to search a contact by name or phone number from a list of contacts.

@Override

    public Filter getFilter() {

        return new Filter() {

            @Override

            protected FilterResults performFiltering(CharSequence charSequence) {

                String charString = charSequence.toString();

                if (charString.isEmpty()) {

                    contactListFiltered = contactList;

                } else {

                    List<Contact> filteredList = new ArrayList<>();

                    for (Contact row : contactList) {

 

                        // name match condition. this might differ depending on your requirement

                        // here we are looking for name or phone number match

                        if (row.getName().toLowerCase().contains(charString.toLowerCase()) || row.getPhone().contains(charSequence)) {

                            filteredList.add(row);

                        }

                    }

 

                    contactListFiltered = filteredList;

                }

 

                FilterResults filterResults = new FilterResults();

                filterResults.values = contactListFiltered;

                return filterResults;

            }

 

            @Override

            protected void publishResults(CharSequence charSequence, FilterResults filterResults) {

                contactListFiltered = (ArrayList<Contact>) filterResults.values;

 

                // refresh the list with filtered data

                notifyDataSetChanged();

            }

        };

    }

Example JSON

For this example I am going to use the json from below url. This json contains list of contacts and each contact will have name, phone number and profile image.

https://api.androidhive.info/json/contacts.json

[{

        "name": "Tom Hardy",

        "image": "https://api.androidhive.info/json/images/tom_hardy.jpg",

        "phone": "(541) 754-3010"

    },

    {

        "name": "Johnny Depp",

        "image": "https://api.androidhive.info/json/images/johnny.jpg",

        "phone": "(452) 839-1210"

    }

]

reating New Project

Now we’ll start with a new project in Android Studio and see how to get the desired search output.

1. Create a new project in Android Studio from File ⇒ New Project and select Basic Activity from templates.

2. Open build.gradle under app folder and add RecyclerView, Glide and Volley dependencies.

build.gradle

dependencies {

    implementation fileTree(dir: 'libs', include: ['*.jar'])

    // ...

 

    // recycler view

    implementation 'com.android.support:recyclerview-v7:26.1.0'

 

    // glide image library

    implementation 'com.github.bumptech.glide:glide:4.3.1'

 

    // volley http library

    implementation 'com.android.volley:volley:1.0.0'

    implementation 'com.google.code.gson:gson:2.6.2'

 

}

Add the below resources to respective strings.xml, dimens.xml, colors.xml files.

strings.xml

<resources>

    <string name="app_name">RecyclerView Search</string>

    <string name="action_settings">Settings</string>

    <string name="toolbar_title">Contacts</string>

    <string name="action_search">Search</string>

    <string name="search_hint">Type name…</string>

</resources>

dimens.xml

<resources>

    <dimen name="fab_margin">16dp</dimen>

    <dimen name="activity_margin">16dp</dimen>

    <dimen name="thumbnail">40dp</dimen>

    <dimen name="row_padding">10dp</dimen>

    <dimen name="contact_name">15dp</dimen>

    <dimen name="contact_number">12dp</dimen>

</resources>

colors.xml

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

<resources>

    <color name="colorPrimary">#111</color>

    <color name="colorPrimaryDark">#FFF</color>

    <color name="colorAccent">#ea3732</color>

    <color name="contact_name">#333333</color>

    <color name="contact_number">#8c8c8c</color>

</resources>

Create a class named MyApplication.java and extend the class from Application. This is a singleton class in which volley is initiated.

public class MyApplication extends Application {

    public static final String TAG = MyApplication.class

            .getSimpleName();

 

    private RequestQueue mRequestQueue;

 

    private static MyApplication mInstance;

 

    @Override

    public void onCreate() {

        super.onCreate();

        mInstance = this;

    }

 

    public static synchronized MyApplication getInstance() {

        return mInstance;

    }

 

    public RequestQueue getRequestQueue() {

        if (mRequestQueue == null) {

            mRequestQueue = Volley.newRequestQueue(getApplicationContext());

        }

 

        return mRequestQueue;

    }

 

    public <T> void addToRequestQueue(Request<T> req, String tag) {

        // set the default tag if tag is empty

        req.setTag(TextUtils.isEmpty(tag) ? TAG : tag);

        getRequestQueue().add(req);

    }

 

    public <T> void addToRequestQueue(Request<T> req) {

        req.setTag(TAG);

        getRequestQueue().add(req);

    }

 

    public void cancelPendingRequests(Object tag) {

        if (mRequestQueue != null) {

            mRequestQueue.cancelAll(tag);

        }

    }

}

Open AndroidManifest.xml and add MyApplication to <application> tag. Also add the INTERNET permission as we are going to make http calls.

AndroidManifest.xml

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

<manifest xmlns:android="http://schemas.android.com/apk/res/android"

    package="info.androidhive.recyclerviewsearch">

 

    <uses-permission android:name="android.permission.INTERNET" />

 

    <application

        android:name=".MyApplication"

        android:allowBackup="true"

        android:icon="@mipmap/ic_launcher"

        android:label="@string/app_name"

        android:roundIcon="@mipmap/ic_launcher_round"

        android:supportsRtl="true"

        android:theme="@style/AppTheme">

        <activity

            android:name=".MainActivity"

            android:label="@string/app_name"

            android:theme="@style/AppTheme.NoActionBar">

 

            <intent-filter>

                <action android:name="android.intent.action.MAIN" />

 

                <category android:name="android.intent.category.LAUNCHER" />

            </intent-filter>

        </activity>

    </application>

 

</manifest>

As we need to parse the json, we need a POJO class to serialize the json. Create a class named Contact.java and add name, image and phone number.

public class Contact {

    String name;

    String image;

    String phone;

 

    public Contact() {

    }

 

    public String getName() {

        return name;

    }

 

    public String getImage() {

        return image;

    }

 

    public String getPhone() {

        return phone;

    }

}

Create a class named MyDividerItemDecoration.java. This step is completely optional but to add some margin to RecyclerView divider. This is a custom divider class to add left margin to divider line.

public class MyDividerItemDecoration  extends RecyclerView.ItemDecoration {

    private static final int[] ATTRS = new int[]{

            android.R.attr.listDivider

    };

 

    public static final int HORIZONTAL_LIST = LinearLayoutManager.HORIZONTAL;

 

    public static final int VERTICAL_LIST = LinearLayoutManager.VERTICAL;

 

    private Drawable mDivider;

    private int mOrientation;

    private Context context;

    private int margin;

 

    public MyDividerItemDecoration(Context context, int orientation, int margin) {

        this.context = context;

        this.margin = margin;

        final TypedArray a = context.obtainStyledAttributes(ATTRS);

        mDivider = a.getDrawable(0);

        a.recycle();

        setOrientation(orientation);

    }

 

    public void setOrientation(int orientation) {

        if (orientation != HORIZONTAL_LIST && orientation != VERTICAL_LIST) {

            throw new IllegalArgumentException("invalid orientation");

        }

        mOrientation = orientation;

    }

 

    @Override

    public void onDrawOver(Canvas c, RecyclerView parent, RecyclerView.State state) {

        if (mOrientation == VERTICAL_LIST) {

            drawVertical(c, parent);

        } else {

            drawHorizontal(c, parent);

        }

    }

 

    public void drawVertical(Canvas c, RecyclerView parent) {

        final int left = parent.getPaddingLeft();

        final int right = parent.getWidth() - parent.getPaddingRight();

 

        final int childCount = parent.getChildCount();

        for (int i = 0; i < childCount; i++) {

            final View child = parent.getChildAt(i);

            final RecyclerView.LayoutParams params = (RecyclerView.LayoutParams) child

                    .getLayoutParams();

            final int top = child.getBottom() + params.bottomMargin;

            final int bottom = top + mDivider.getIntrinsicHeight();

            mDivider.setBounds(left + dpToPx(margin), top, right, bottom);

            mDivider.draw(c);

        }

    }

 

    public void drawHorizontal(Canvas c, RecyclerView parent) {

        final int top = parent.getPaddingTop();

        final int bottom = parent.getHeight() - parent.getPaddingBottom();

 

        final int childCount = parent.getChildCount();

        for (int i = 0; i < childCount; i++) {

            final View child = parent.getChildAt(i);

            final RecyclerView.LayoutParams params = (RecyclerView.LayoutParams) child

                    .getLayoutParams();

            final int left = child.getRight() + params.rightMargin;

            final int right = left + mDivider.getIntrinsicHeight();

            mDivider.setBounds(left, top + dpToPx(margin), right, bottom - dpToPx(margin));

            mDivider.draw(c);

        }

    }

 

    @Override

    public void getItemOffsets(Rect outRect, View view, RecyclerView parent, RecyclerView.State state) {

        if (mOrientation == VERTICAL_LIST) {

            outRect.set(0, 0, 0, mDivider.getIntrinsicHeight());

        } else {

            outRect.set(0, 0, mDivider.getIntrinsicWidth(), 0);

        }

    }

 

    private int dpToPx(int dp) {

        Resources r = context.getResources();

        return Math.round(TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, dp, r.getDisplayMetrics()));

    }

}

Writing the Adapter class with Filter

Now as the resources ready, let’s start writing the adapter class. You need to particularly focus on this class as it is main component in this article.

9. Create a layout named user_row_item.xml and add the below layout. This layout renders the single contact item in the list. This layout contains two TextViews to render name, phone number and an ImageView to display the profile image.

user_row_item.xml

<?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="wrap_content"

    android:background="?attr/selectableItemBackground"

    android:clickable="true"

    android:paddingBottom="@dimen/row_padding"

    android:paddingLeft="@dimen/activity_margin"

    android:paddingRight="@dimen/activity_margin"

    android:paddingTop="@dimen/row_padding">

 

    <ImageView

        android:id="@+id/thumbnail"

        android:layout_width="@dimen/thumbnail"

        android:layout_height="@dimen/thumbnail"

        android:layout_centerVertical="true"

        android:layout_marginRight="@dimen/row_padding" />

 

    <TextView

        android:id="@+id/name"

        android:layout_width="wrap_content"

        android:layout_height="wrap_content"

        android:layout_toRightOf="@id/thumbnail"

        android:fontFamily="sans-serif-medium"

        android:textColor="@color/contact_name"

        android:textSize="@dimen/contact_name" />

 

    <TextView

        android:id="@+id/phone"

        android:layout_width="wrap_content"

        android:layout_height="wrap_content"

        android:layout_below="@id/name"

        android:layout_toRightOf="@id/thumbnail"

        android:textColor="@color/contact_number"

        android:textSize="@dimen/contact_number" />

 

</RelativeLayout>

10. Create class named ContactsAdapter.java and implement the class from Filterable which asks you to override the getFilter() method.

In getFilter() method, the search string is passed to performFiltering() method. The search for a contact by name or mobile number is performed using query string.

You will have to adjust the search condition depending on your app requirement.

ContactsAdapterListener interface provides onContactSelected() callback method whenever a contact is selected from the list.

public class ContactsAdapter extends RecyclerView.Adapter<ContactsAdapter.MyViewHolder>

        implements Filterable {

    private Context context;

    private List<Contact> contactList;

    private List<Contact> contactListFiltered;

    private ContactsAdapterListener listener;

 

    public class MyViewHolder extends RecyclerView.ViewHolder {

        public TextView name, phone;

        public ImageView thumbnail;

 

        public MyViewHolder(View view) {

            super(view);

            name = view.findViewById(R.id.name);

            phone = view.findViewById(R.id.phone);

            thumbnail = view.findViewById(R.id.thumbnail);

 

            view.setOnClickListener(new View.OnClickListener() {

                @Override

                public void onClick(View view) {

                    // send selected contact in callback

                    listener.onContactSelected(contactListFiltered.get(getAdapterPosition()));

                }

            });

        }

    }

 

 

    public ContactsAdapter(Context context, List<Contact> contactList, ContactsAdapterListener listener) {

        this.context = context;

        this.listener = listener;

        this.contactList = contactList;

        this.contactListFiltered = contactList;

    }

 

    @Override

    public MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {

        View itemView = LayoutInflater.from(parent.getContext())

                .inflate(R.layout.user_row_item, parent, false);

 

        return new MyViewHolder(itemView);

    }

 

    @Override

    public void onBindViewHolder(MyViewHolder holder, final int position) {

        final Contact contact = contactListFiltered.get(position);

        holder.name.setText(contact.getName());

        holder.phone.setText(contact.getPhone());

 

        Glide.with(context)

                .load(contact.getImage())

                .apply(RequestOptions.circleCropTransform())

                .into(holder.thumbnail);

    }

 

    @Override

    public int getItemCount() {

        return contactListFiltered.size();

    }

 

    @Override

    public Filter getFilter() {

        return new Filter() {

            @Override

            protected FilterResults performFiltering(CharSequence charSequence) {

                String charString = charSequence.toString();

                if (charString.isEmpty()) {

                    contactListFiltered = contactList;

                } else {

                    List<Contact> filteredList = new ArrayList<>();

                    for (Contact row : contactList) {

 

                        // name match condition. this might differ depending on your requirement

                        // here we are looking for name or phone number match

                        if (row.getName().toLowerCase().contains(charString.toLowerCase()) || row.getPhone().contains(charSequence)) {

                            filteredList.add(row);

                        }

                    }

 

                    contactListFiltered = filteredList;

                }

 

                FilterResults filterResults = new FilterResults();

                filterResults.values = contactListFiltered;

                return filterResults;

            }

 

            @Override

            protected void publishResults(CharSequence charSequence, FilterResults filterResults) {

                contactListFiltered = (ArrayList<Contact>) filterResults.values;

                notifyDataSetChanged();

            }

        };

    }

 

    public interface ContactsAdapterListener {

        void onContactSelected(Contact contact);

    }

}

Adding Search Widget and Filtering List

Now everything is ready. All we have to do is, enable SearchView in Toolbar, render the RecyclerView by parsing the json and pass the search query to adapter.

11. Open / create menu_main.xml located under res ⇒ menus and add the SearchView widget and make it always visible.

menu_main.xml

<menu 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"

    tools:context="info.androidhive.recyclerviewsearch.MainActivity">

    <item

        android:id="@+id/action_search"

        android:icon="@drawable/ic_search_black_24dp"

        android:orderInCategory="100"

        android:title="@string/action_search"

        app:showAsAction="always"

        app:actionViewClass="android.support.v7.widget.SearchView" />

</menu>

Under res ⇒ xml folder, create an xml file named searchable.xml (If xml folder doesn’t exists, create a new one)

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

<searchable xmlns:android="http://schemas.android.com/apk/res/android"

    android:hint="@string/search_hint"

    android:label="@string/app_name" />

Open AndroidManifest.xml and configure the search as shown below.

AndroidManifest.xml

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

<manifest xmlns:android="http://schemas.android.com/apk/res/android"

    package="info.androidhive.recyclerviewsearch">

 

    <uses-permission android:name="android.permission.INTERNET" />

 

    <application ...>

        <activity

            android:name=".MainActivity"

            android:label="@string/app_name"

            android:theme="@style/AppTheme.NoActionBar">

 

            <meta-data

                android:name="android.app.searchable"

                android:resource="@xml/searchable" />

 

            <intent-filter>

                <action android:name="android.intent.action.SEARCH" />

            </intent-filter>

 

            <intent-filter>

                <action android:name="android.intent.action.MAIN" />

 

                <category android:name="android.intent.category.LAUNCHER" />

            </intent-filter>

        </activity>

    </application>

 

</manifest>

Open the layout files of main activity activity_main.xml and content_main.xml and add RecyclerView element.

activity_main.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="info.androidhive.recyclerviewsearch.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="@android:color/white"

            app:popupTheme="@style/AppTheme.PopupOverlay" />

 

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

 

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

 

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

content_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"

    app:layout_behavior="@string/appbar_scrolling_view_behavior"

    tools:context="info.androidhive.recyclerviewsearch.MainActivity"

    tools:showIn="@layout/activity_main">

 

    <android.support.v7.widget.RecyclerView

        android:id="@+id/recycler_view"

        android:layout_width="match_parent"

        android:layout_height="wrap_content"

        android:scrollbars="vertical" />

 

</RelativeLayout>

 Finally open the MainActivity.java and add the code as shown below.

 public class MainActivity extends AppCompatActivity implements ContactsAdapter.ContactsAdapterListener {

    private static final String TAG = MainActivity.class.getSimpleName();

    private RecyclerView recyclerView;

    private List<Contact> contactList;

    private ContactsAdapter mAdapter;

    private SearchView searchView;

 

    // url to fetch contacts json

    private static final String URL = "https://api.androidhive.info/json/contacts.json";

 

    @Override

    protected void onCreate(Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);

        setContentView(R.layout.activity_main);

        Toolbar toolbar = findViewById(R.id.toolbar);

        setSupportActionBar(toolbar);

 

        // toolbar fancy stuff

        getSupportActionBar().setDisplayHomeAsUpEnabled(true);

        getSupportActionBar().setTitle(R.string.toolbar_title);

 

        recyclerView = findViewById(R.id.recycler_view);

        contactList = new ArrayList<>();

        mAdapter = new ContactsAdapter(this, contactList, this);

 

        // white background notification bar

        whiteNotificationBar(recyclerView);

 

        RecyclerView.LayoutManager mLayoutManager = new LinearLayoutManager(getApplicationContext());

        recyclerView.setLayoutManager(mLayoutManager);

        recyclerView.setItemAnimator(new DefaultItemAnimator());

        recyclerView.addItemDecoration(new MyDividerItemDecoration(this, DividerItemDecoration.VERTICAL, 36));

        recyclerView.setAdapter(mAdapter);

 

        fetchContacts();

    }

 

    /**

     * fetches json by making http calls

     */

    private void fetchContacts() {

        JsonArrayRequest request = new JsonArrayRequest(URL,

                new Response.Listener<JSONArray>() {

                    @Override

                    public void onResponse(JSONArray response) {

                        if (response == null) {

                            Toast.makeText(getApplicationContext(), "Couldn't fetch the contacts! Pleas try again.", Toast.LENGTH_LONG).show();

                            return;

                        }

 

                        List<Contact> items = new Gson().fromJson(response.toString(), new TypeToken<List<Contact>>() {

                        }.getType());

 

                        // adding contacts to contacts list

                        contactList.clear();

                        contactList.addAll(items);

 

                        // refreshing recycler view

                        mAdapter.notifyDataSetChanged();

                    }

                }, new Response.ErrorListener() {

            @Override

            public void onErrorResponse(VolleyError error) {

                // error in getting json

                Log.e(TAG, "Error: " + error.getMessage());

                Toast.makeText(getApplicationContext(), "Error: " + error.getMessage(), Toast.LENGTH_SHORT).show();

            }

        });

 

        MyApplication.getInstance().addToRequestQueue(request);

    }

 

    @Override

    public boolean onCreateOptionsMenu(Menu menu) {

        getMenuInflater().inflate(R.menu.menu_main, menu);

 

        // Associate searchable configuration with the SearchView

        SearchManager searchManager = (SearchManager) getSystemService(Context.SEARCH_SERVICE);

        searchView = (SearchView) menu.findItem(R.id.action_search)

                .getActionView();

        searchView.setSearchableInfo(searchManager

                .getSearchableInfo(getComponentName()));

        searchView.setMaxWidth(Integer.MAX_VALUE);

 

        // listening to search query text change

        searchView.setOnQueryTextListener(new SearchView.OnQueryTextListener() {

            @Override

            public boolean onQueryTextSubmit(String query) {

                // filter recycler view when query submitted

                mAdapter.getFilter().filter(query);

                return false;

            }

 

            @Override

            public boolean onQueryTextChange(String query) {

                // filter recycler view when text is changed

                mAdapter.getFilter().filter(query);

                return false;

            }

        });

        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_search) {

            return true;

        }

 

        return super.onOptionsItemSelected(item);

    }

 

    @Override

    public void onBackPressed() {

        // close search view on back button pressed

        if (!searchView.isIconified()) {

            searchView.setIconified(true);

            return;

        }

        super.onBackPressed();

    }

 

    private void whiteNotificationBar(View view) {

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {

            int flags = view.getSystemUiVisibility();

            flags |= View.SYSTEM_UI_FLAG_LIGHT_STATUS_BAR;

            view.setSystemUiVisibility(flags);

            getWindow().setStatusBarColor(Color.WHITE);

        }

    }

 

    @Override

    public void onContactSelected(Contact contact) {

        Toast.makeText(getApplicationContext(), "Selected: " + contact.getName() + ", " + contact.getPhone(), Toast.LENGTH_LONG).show();

    }

}

Friday, November 27, 2020

Customize Android home screen for beginners

Android is an open-source operating system and comes with a variety of customizations tailored to the way that smartphone manufacturers make their own.Even on your Android phone's home screen, you can do one too. Some convenient optional features, such as changing the wallpaper, choosing a new interface, adding widgets, creating themes ...

Customize Android home screen for beginners

Quite a few widgets that you can tweak right on the home screen without having to go into the settings menu. Below, we will send you a few customization tips right on the main screen.

Customizations you can do on the Android home screen

1. Add Widget

For Android users, widgets are a great way to customize the home screen based on their needs.

This feature provides widgets such as app shortcuts, prominent notifications, easy-to-understand screenshot information, and continuous updates throughout the day. Some widgets may even display less / more data, depending on what information you want to receive from the application.

How to add widgets to an Android device

1. Press and hold firmly on an empty part of the home screen.

2. A window pops up, click on Widgets.

3. There will be a menu showing all available widgets based on an application you have downloaded to your phone.

4. Press hard on the widget you want to add. Then you will be taken back to the home screen, drag and drop arbitrary widgets on the screen.

How to change widget size on Android home screen

1. To get the desired widget size, press firmly on the widget on the home screen.

2. A white dialog box appears with a custom icon appearing around the widget. Drag in / out to change the size of the widget.

3. Then, click on the space outside the widget, your screen will get the desired widget size.

2. Customize wallpaper for phone

To customize the wallpaper for your Android phone, press for about 5 seconds on the screen until the options appear below. Click on the Wallpaper, followed by the wallpaper menu, a list of interfaces will appear, besides you can also choose to change icons by clicking on Icons.

3. Create folders and shortcuts

Your home screen has quite a few icons, you can go to the application list menu, then touch and hold the icons in this list. Next move it outside of the home screen and place the app's icon anywhere.

If you move too many icons and find them a bit cluttered, you can group them into one or more folders on the home screen, just hold and move any icon to another icon. Immediately the two icons will be converted to an unnamed folder, you can click on the Enter folder name and write the name you want to change, for example the folder containing only games you can name is Game, folder Only contains a photography app set to take a picture.

4. Add Launcher app

The Launcher applications currently support users a lot in tweaking the home screen. Includes more widget options, more themes and features. You can also choose more home screens than default is 5, the most popular Launcher apps currently are Nova Launcher, APUS Launcher.

Those are a few tips to help you customize your home screen, making your home screen operate in a much more convenient way.

How to use Android Picture-in-Picture mode

 Picture-in-Picture mode Android lets you shrink the video and see picture-in-picture mode, watch the video in a different interface so you can do other things. Currently, this feature is available on Android versions 8 and above, so that users can activate it. The following article will guide you on how to enable Picture-in-Picture mode and use picture-in-picture viewing.

1. How to activate Picture-in-Picture Android

Step 1:

In the interface Settings on the device, you click on Apps and notifications and then click on Access special applications.

Step 2:

In the next interface, click Picture in picture and will see supported applications playing Picture-in-Picture mode.

Note:

This feature only works on certain supported apps.

Some supporting applications require manual activation to enable this feature.

2. How to view picture-in-picture videos on Android

For applications that support picture-in-picture mode, you basically just need to press the Home key to see picture-in-picture video.

How to use Android Picture-in-Picture mode

Some other apps will need to be set up manually, for example with the Chrome browser. You open the website in Chrome and then click on the 3 dot icon, select Website for desktop. Then open the video on the web page in full screen mode.

While watching the video, click the Home icon, the video immediately shows in thumbnail mode as below. You can browse the web while watching videos as you normally would.

To watch the video in normal screen mode, click on the video and then click on the zoom icon.

How to click camera programmatically in android

 How to click camera programmatically in android

Step 1 − Create a new project in Android Studio, go to File ⇒ New Project and fill all required details to create a new project.

Step 2 − Add the following code to res/layout/activity_main.xml.

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

<LinearLayout

   xmlns:android="http://schemas.android.com/apk/res/android"

   android:orientation="vertical"

   android:layout_width="match_parent"

   android:gravity="center_horizontal"

   android:layout_height="match_parent">

   <TextView

      android:layout_width="wrap_content"

      android:layout_height="wrap_content"

      android:text="Click the below button to take photo from camera"/>

   <ImageView

      android:id="@+id/imageView"

      android:scaleType="centerCrop"

      android:layout_width="300dp"

      android:layout_height="400dp"

      android:src="@drawable/ic_image_black"

      android:layout_marginTop="16dp"/>

   <Button

      android:id="@+id/btnCaptureImage"

      android:text="Capture Image"

      android:layout_width="match_parent"

      android:layout_height="wrap_content" />

</LinearLayout>

Step 3 − Add the following code to src/MainActivity.java

public class MainActivity extends AppCompatActivity {

   private static final int PERMISSION_CODE = 1000;

   Button mCaptureBtn;

   ImageView mImageView;

   Uri imageUri;

   private int IMAGE_CAPTURE_CODE = 1001;

   @Override

   protected void onCreate(Bundle savedInstanceState) {

      super.onCreate(savedInstanceState);

      setContentView(R.layout.activity_main);

      mImageView = findViewById(R.id.imageView);

      mCaptureBtn = findViewById(R.id.btnCaptureImage);

      mCaptureBtn.setOnClickListener(new

      View.OnClickListener() {

         @Override

         public void onClick(View v) {

            if (Build.VERSION.SDK_INT>=Build.VERSION_CODES.M){

               if (checkSelfPermission(Manifest.permission.CAMERA)==PackageManager.PERMISSION_GRANTED(Manifest.permission.CAMERA).PERMISSION_DENIED){

                  String[] permission = {Manifest.permission.CAMERA,Manifest.permission.WRITE_EXTERNAL_STORAGE};

                  requestPermissions(permission,PERMISSION_CODE);

               } else{

                  openCamera();

               }

            }

         }

      });

   }

   private void openCamera() {

      ContentValues values = new ContentValues();

      values.put(MediaStore.Images.Media.TITLE, "New Picture");

      values.put(MediaStore.Images.Media.DESCRIPTION, "From the Camera");

      imageUri = getContentResolver().insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, values);

      Intent cameraIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);

      cameraIntent.putExtra(MediaStore.EXTRA_OUTPUT, imageUri);

      startActivityForResult(cameraIntent, IMAGE_CAPTURE_CODE);

   }

   public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {

      switch (requestCode){

         case PERMISSION_CODE:{

            if (grantResults.length > 0 && grantResults[0]==PackageManager.PERMISSION_GRANTED){

               openCamera();

            } else {

               Toast.makeText(this, "Permissiondenied...", Toast.LENGTH_SHORT).show();

            }

         }

      }

   }

   @Override

   protected void onActivityResult(int requestCode, intresultCode, Intent data) {

      if (resultCode == RESULT_OK){

         mImageView.setImageURI(imageUri);

      }

   }

}

Step 4 − Add the following code to androidManifest.xml

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

<manifest xmlns:android="http://schemas.android.com/apk/res/android" package="app.com.sample">

   <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>

   <uses-permission android:name="android.permission.CAMERA"/>

   <application

      android:allowBackup="true"

      android:icon="@mipmap/ic_launcher"

      android:label="@string/app_name"

      android:roundIcon="@mipmap/ic_launcher_round"

      android:supportsRtl="true"

      android:theme="@style/AppTheme">

      <activity android:name=".MainActivity">

         <intent-filter>

            <action android:name="android.intent.action.MAIN" />

            <category android:name="android.intent.category.LAUNCHER" />

         </intent-filter>

      </activity>

   </application>

</manifest>

How to click camera programmatically in android

Draw dash line along path, with DashPathEffect

 Draw dash line along path, with DashPathEffect

Create class custom MyView.java

public class MyView extends View {

 Paint paint;

 Path path;

 public MyView(Context context) {

  super(context);

  init();

 }

 public MyView(Context context, AttributeSet attrs) {

  super(context, attrs);

  init();

 }

 public MyView(Context context, AttributeSet attrs, int defStyle) {

  super(context, attrs, defStyle);

  init();

 }

 private void init() {

  paint = new Paint();

  paint.setColor(Color.BLUE);

  paint.setStrokeWidth(10);

  paint.setStyle(Paint.Style.STROKE);

  path = new Path();

  path.moveTo(50, 50);

  path.lineTo(50, 500);

  path.lineTo(200, 500);

  path.lineTo(200, 300);

  path.lineTo(350, 300);

  float[] intervals = new float[]{50.0f, 20.0f};

  float phase = 0;

  DashPathEffect dashPathEffect = 

    new DashPathEffect(intervals, phase);

  paint.setPathEffect(dashPathEffect);

 }

 @Override

 protected void onDraw(Canvas canvas) {

  super.onDraw(canvas);

  canvas.drawPath(path, paint);

 }

}

 

Draw dash line along path, with DashPathEffect

Draw path on custom View Android Example

Draw path on custom View Android Example

Create MyView.java

public class MyView extends View {

 Paint paint;

 Path path;

 public MyView(Context context) {

  super(context);

  init();

 }

 public MyView(Context context, AttributeSet attrs) {

  super(context, attrs);

  init();

 }

 public MyView(Context context, AttributeSet attrs, int defStyle) {

  super(context, attrs, defStyle);

  init();

 }

 private void init() {

  paint = new Paint();

  paint.setColor(Color.BLUE);

  paint.setStrokeWidth(10);

  paint.setStyle(Paint.Style.STROKE);

  path = new Path();

  path.moveTo(50, 50);

  path.lineTo(50, 500);

  path.lineTo(200, 500);

  path.lineTo(200, 300);

  path.lineTo(350, 300);

 }

 @Override

 protected void onDraw(Canvas canvas) {

  super.onDraw(canvas);

  canvas.drawPath(path, paint);

 }

}

Layout activity_main.xml

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"

    xmlns:tools="http://schemas.android.com/tools"

    android:layout_width="match_parent"

    android:layout_height="match_parent"

    android:paddingBottom="@dimen/activity_vertical_margin"

    android:paddingLeft="@dimen/activity_horizontal_margin"

    android:paddingRight="@dimen/activity_horizontal_margin"

    android:paddingTop="@dimen/activity_vertical_margin"

    android:orientation="vertical"

    tools:context="com.example.androidview.MainActivity" >

    <TextView

        android:layout_width="wrap_content"

        android:layout_height="wrap_content"

        android:text="android-coding.blogspot.com" />

    <com.example.androidview.MyView

        android:layout_width="match_parent"

        android:layout_height="match_parent" />

</LinearLayout>

Create class MainActivity.java

public class MainActivity extends Activity {

 @Override

 protected void onCreate(Bundle savedInstanceState) {

  super.onCreate(savedInstanceState);

  setContentView(R.layout.activity_main);

 }

}

Draw path on custom View Android Example

Monday, November 23, 2020

Android pass large data between activities

Issue: Passing large data to second Activity, As suggested by google android guide, you could use static fields or singletons to share data between activities. You can pass data between activities in application in 3 ways. Intent; SharedPreferences; Application; passing data in intent have some limit. For large amount of data you can use Application level data sharing and by storing it in SharedPreference makes your app size increase.

Android pass large data between activities

How to pass large data between activities in Android?, This example demonstrate about How to pass large data between activities in AndroidStep 1 − Create a new project in Android Studio, go to  Sending Data Between Activities in Android Android Intents are objects used to trigger actions from other Android Activities. One of the most common uses of Intents is to open a new Activity in your app. Often, you will want to pass information to the new Activity.

How do you pass large data between activities and safeguard , +1, use an ORM android database lib. Like Realm or DBFlow or another ORM. Where do the images come from? Passing images by intent means holding them in  Pass data between fragments Starting with Fragment 1.3.0-alpha04 , each FragmentManager implements FragmentResultOwner . This means that a FragmentManager can act as a central store for fragment results.

How to pass list in bundle android

Pass list to intent in android java Code Example, You will need to have ValueActivity implement Parcelable interface and you will need to implement writeToParcel() the CREATOR and a  To put the list into the Bundle, use: bundle.putParcelableArrayList("list", list); To get the list out of the Bundle in the target activity, use: 

List<ValueActivity> = listbundle.getParcelableArrayList("list");

How to passing list<> in bundle, Passing custom List of data using Bundle · android list android-fragments bundle custom-object. I'm developing a simple app, that contains  You need to use bundle.putParcelableArrayList () and instantiate your list as private ArrayList<InfoProduct> product;.Also make sure that InfoProduct is Parcelable. Answer 3 You can pass the arraylist of your custom define object either by implementing serializable or parcelable. Android: Difference between Parcelable and Serializable?

Passing custom List of data using Bundle, Best Java code snippets using android.os.Bundle.putParcelableArrayList Inserts a List of Parcelable values into the mapping of this Bundle, * replacing any Pass an ordered list of desired aspect ratios that should be available for a user. In this article, we are going to look at Android Parcelable example by passing objects via bundle between activities and fragments. Although there are no prerequisites for this tutorial, here I am going to take the Movie Board project that we’ve been building in our previous posts and implement Parcelable to it and pass the objects via bundle.

Send list through intent android

 Intent.putExtra List, 4 Answers. Declare List private List<String> test; Init List at appropriate place. test = new ArrayList<String>(); and add data as appropriate to test . Pass to intent as follows: Intent intent = getIntent(); intent. putStringArrayListExtra("test", (ArrayList<String>) test); Retrieve data as follows: Assuming that your List is a list of strings make data an ArrayList<String> and use intent.putStringArrayListExtra("data", data) Here is a skeleton of the code you need: Declare List. private List<String> test; Init List at appropriate place. test = new ArrayList<String>(); and add data as appropriate to test. Pass to intent as follows:

How to pass ArrayList of Objects from one to another activity using , add implemets method in android studio by Alt+Enter Now to pass it to the intent. getBird(); Intent intent = new Intent(Current.this, Transfer.class); Bundle bundle List<Question> mQuestionList = new ArrayList<Question>; mQuestionsList  How to send email in android using intent We can easily send email in android via intent. You need to write few lines of code only as given below Intent email = new Intent (Intent.ACTION_SEND);

Passing a List from one Activity to another, You can pass an ArrayList<E> the same way, if the E type is Serializable . You would call the putExtra (String name, Serializable value) of Intent  How to send & receive ListView selected value From one activity to next and set into EditText using Intent. In this tutorial we would going to create a simple ListView using array adapter.

Pass custom list in intent android

How to pass Custom List Object using intent, I am working on android application and in that I want to pass a Cutom list Object to other activity via intent. I have made that CustomList class  I am trying to pass an arrayList to another activity using intents. Here is the code in the first activity. case R.id.editButton: Toast.makeText(this, "edit was clicked", Toast.LENGTH_LONG

Android, android documentation: Passing custom object between activities. //Getting MyObject List Intent mIntent = getIntent(); ArrayList<MyObjects> mUsers = mIntent​. In the blog, we have shown you how to pass the List of CustomObjects to the Activity and fragment. In this technique, we have used the Serialization for the list passing. Serialization is the process of converting an object into a stream of bytes in order to store the object or transmit it to memory, a database, or a file.

pass list to intent in android java Code Example, “pass list to intent in android java” Code Answer. Intent intent = new Intent(getApplicationContext(),YourActivity. class); Bundle bundle = new Bundle(); bundle. putParcelable("data", sharedBookingObject); intent. putExtras(bundle); startActivity(intent); private List<String> test; Init List at appropriate place. test = new ArrayList<String> (); and add data as appropriate to test. Pass to intent as follows: Intent intent = getIntent(); intent.putStringArrayListExtra("test", (ArrayList<String>) test); Retrieve data as follows:

Send arraylist from one activity to another

How to pass ArrayList<CustomeObject> from one activity to another , 4 Answers. You can pass an ArrayList<E> the same way, if the E type is Serializable . You would call the putExtra (String name, Serializable value) of Intent to store, and getSerializableExtra (String name) for retrieval. I want to send Following ArrayList from one activity to another please help. ContactBean m_objUserDetails = new ContactBean(); ArrayList<ContactBean> ContactLis = new ArrayList<ContactBean>(); I am sending the above arraylist after adding data in it as follows

How to pass ArrayList of Objects from one to another activity using , Between Activity: Worked for me ArrayList<Object> object = new ArrayList<Object​>(); Intent intent = new Intent(Current.class, Transfer.class); Bundle args = new  This example demonstrates how do I pass an arrayList to another activity using intends in android. Step 1 − Create a new project in Android Studio, go to File ⇒ New Project and fill all required details to create a new project. Step 2 − Add the following code to res/layout/activity_main.xml.

How to pass an arrayList to another activity using intents in Android?, This example demonstrates how do I pass an arrayList to another To run the app from android studio, open one of your project's activity files  To pass ArrayList from one activity to another activity, one should include intent.putStringArrayListExtra(KEY, list); //where list is ArrayList which you want to pass before starting the activity.And to get the ArrayList in another activity include

How to pass arraylist from adapter to activity in android

 Pass ArrayList from Adapter to Activity on a Button Click, This is from FirstActivity Parsing Json in ArrayList JSONArray This is the Adapter On Click Bundle Pass public class This the Detail Activity Receiving End Parcel.writeArrayMapInternal(Parcel.java:665) at android.os. @Developers, if you add parameter to adapter's constructor, you should pass actual argument from calling code: mAdapter = new MainAdapterlista_show, dashboard.this, dashboard.this) (I suppose, dashboard is your activity) - see pt 4.

How to access an arrayList from an adapter to an activity?, Write a get method inside your adapter then call it from your activity. public ArrayList<Object> getArrayList(){ return yourArrayList; }. Inside your  This example demonstrates how to pass an arrayList to another activity using intents in Android Kotlin. Step 1 − Create a new project in Android Studio, go to File ? New Project and fill all required details to create a new project.

Pass ArrayList from Adapter to Activity on a Button Click, Adapter<MaintenanceAdapter.ViewHolder> { private Context mContext; List<​MaintanceModel> maintanceModelList = new ArrayList<MaintanceModel>(); public  Passing Java Objects in Android is made easy by implementing the Parcelable interface.The With the help of the parcelable interface your can write your object to a parcel or read from a parcel, that way you can easily pass it around when calling the activity using bundles.

How to pass arraylist using bundle in android

 Help passing an ArrayList of Objects to a new Activity, Android passes Object in Bundle by serializing and deserializing (via Serializable or Parcelable). So all of your Objects you want to pass in a  Or the objects can implement Serializable and use the method putSerializable() to add the ArrayList, ie bundle.putSerializable("arraylist", arraylist); Android passes Object in Bundle by serializing and deserializing (via Serializable or Parcelable). So all of your Objects you want to pass in a Bundle must implement one of those two interfaces.

How to pass ArrayList of Objects from one to another activity using , getBundleExtra("BUNDLE"); ArrayList<Object> object = (ArrayList<Object>) args. Using Parcelable to pass data between Activity. This usually add implemets method in android studio by Alt+Enter. Note: A Now to pass it to the intent. You need to use bundle.putParcelableArrayList() and instantiate your list as private ArrayList<InfoProduct> product;.Also make sure that InfoProduct is Parcelable. Answer 3 You can pass the arraylist of your custom define object either by implementing serializable or parcelable .

android.os.Bundle.putParcelableArrayList java code examples , public I parcelableArrayListArg(String key, ArrayList value) { args. Best Java code snippets using android.os.Bundle.putParcelableArrayList (Showing top 20 Pass an ordered list of desired aspect ratios that should be available for a user. This example demonstrates how do I pass an arrayList to another activity using intends in android. Step 1 − Create a new project in Android Studio, go to File ⇒ New Project and fill all required details to create a new project.

How to pass arraylist in intent putextra

 Intent putExtra ArrayList<NameValuePair>

As others have noted, when you want to pass an array as an intent extra, the elements need to implement Serializable . In your case, the  1. You need to pass a Object array as a Serializable into the intent. The Object array must consist of objects that are inturn Serializable. 

ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair> (); nameValuePairs.add(new BasicNameValuePair("first_name", first_name)); nameValuePairs.add(new BasicNameValuePair("last_name", last_name)); nameValuePairs.add(new BasicNameValuePair("email", email));

nameValuePairs.add(new BasicNameValuePair("password", password));

How to pass ArrayList of Objects from one to

 putSerializable("ARRAYLIST",(Serializable)object);

 intent.putExtra("BUNDLE",​args); 

 startActivity(intent);

In the Transfer.class. Intent intent = getIntent(); Bundle​  I have done this one by Passing ArrayList in form of String. Add compile 'com.google.code.gson:gson:2.2.4' in dependencies block build.gradle. Click on Sync Project with Gradle Files. Cars.java: public class Cars { public String id, name; } FirstActivity.java. When you want to pass ArrayList:

Intent.putextra

How to use Intents & Extras to pass data between , Intents in android offer this convenient way to pass data between into the Intent object, we use the method defined in the Intent class putExtra() or We can also pass Java class objects through bundles, maybe an ArrayList,  This example demonstrates how do I pass an arrayList to another activity using intends in android.

Tuesday, November 17, 2020

Cute Wallpaper for Android

Cute Wallpaper is an application to share beautiful wallpapers for your phone, with images of 3D, HD, 4K image quality.

With thousands of beautiful pictures that we are designed exclusively for you to install on your phone so that you can see cute pictures you can think comfortably.

Cute Wallpaper

**Features of cute wallpapers**

Set wallpaper to home screen and lock screen

There are many different images and genres

3D, 4K, HD quality images

You can download the image above in the Download section

The application is easy to use

Show actual image

Light image loading capacity

** Future features **

Will update Demo install wallpaper

Upload images to the user

Saturday, November 14, 2020

Android get Bitmap or sound from assets

Android get Bitmap or sound from assets

I need to get Bitmap and sound from assets. I try to do like this:

BitmapFactory.decodeFile("file:///android_asset/Files/Numbers/l1.png");

getBitmapFromAsset("Files/Numbers/l1.png");

    private Bitmap getBitmapFromAsset(String strName) {

        AssetManager assetManager = getAssets();

        InputStream istr = null;

        try {

            istr = assetManager.open(strName);

        } catch (IOException e) {

            e.printStackTrace();

        }

        Bitmap bitmap = BitmapFactory.decodeStream(istr);

        return bitmap;

    }

But I get just free space, not image.

Answers

public static Bitmap getBitmapFromAsset(Context context, String filePath) {

    AssetManager assetManager = context.getAssets();


    InputStream istr;

    Bitmap bitmap = null;

    try {

        istr = assetManager.open(filePath);

        bitmap = BitmapFactory.decodeStream(istr);

    } catch (IOException e) {

        // handle exception

    }


    return bitmap;

}

How to load an image from a file and set on an ImageView

 If you’re working with an Android application, this source code works as a way to load an image from a file:

Bitmap bitmap = BitmapFactory.decodeFile(pathToPicture);

The Bitmap and BitmapFactory classes are located in the android.graphics package:

import android.graphics.Bitmap;

import android.graphics.BitmapFactory;

Assuming that your pathToPicture is correct, you can then add this bitmap image to an ImageView like this:

ImageView imageView = (ImageView) getActivity().findViewById(R.id.imageView);

imageView.setImageBitmap(BitmapFactory.decodeFile(pathToPicture));

As shown, the setImageBitmap method is another key to this solution.

I’m currently using this approach to let users choose an image from their image/photo gallery, which is where I get the file path.

Android Image loading in RecyclerView using Picasso

 Android Image loading in RecyclerView using Picasso

In our previous tutorials we learned to implement a simple RecyclerView. In this tutorial we are going to learn how to load image from Internet to RecyclerView using Picasso library.

The dependency for Picasso is

compile 'com.squareup.picasso:picasso:2.5.2'

The other dependencies we require,

compile 'com.android.support:recyclerview-v7:23.1.1'

compile 'com.android.support:cardview-v7:23.1.1'

compile 'com.android.support:appcompat-v7:23.1.1'

compile 'com.android.support:design:23.1.1'

The complete build.gradle

apply plugin: 'com.android.application'

android {

    compileSdkVersion 23

    buildToolsVersion "23.0.2"


    defaultConfig {

        applicationId "com.learn2crack.loadimage"

        minSdkVersion 16

        targetSdkVersion 23

        versionCode 1

        versionName "1.0"

    }

    buildTypes {

        release {

            minifyEnabled false

            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'

        }

    }

}


dependencies {

    compile fileTree(dir: 'libs', include: ['*.jar'])

    testCompile 'junit:junit:4.12'

    compile 'com.android.support:recyclerview-v7:23.1.1'

    compile 'com.android.support:cardview-v7:23.1.1'

    compile 'com.squareup.picasso:picasso:2.5.2'

    compile 'com.android.support:appcompat-v7:23.1.1'

    compile 'com.android.support:design:23.1.1'

}

activity_main.xml

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

<android.support.design.widget.CoordinatorLayout xmlns:android="http://schemas.android.com/apk/res/android"

    xmlns:tools="http://schemas.android.com/tools"

    android:layout_width="match_parent"

    android:layout_height="match_parent"

    android:fitsSystemWindows="true"

    tools:context="com.learn2crack.loadimage.MainActivity">


    <android.support.v7.widget.RecyclerView

        android:id="@+id/card_recycler_view"

        android:scrollbars="vertical"

        android:layout_width="match_parent"

        android:layout_height="match_parent"/>


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

row_layout.xml

<android.support.v7.widget.CardView xmlns:card_view="http://schemas.android.com/apk/res-auto"

    xmlns:android="http://schemas.android.com/apk/res/android"

    android:layout_width="match_parent"

    android:layout_height="wrap_content"

    android:layout_marginTop="5dp"

    android:layout_marginLeft="5dp"

    android:layout_marginRight="5dp"

    card_view:cardCornerRadius="5dp">


    <RelativeLayout

        android:layout_marginLeft="20dp"

        android:layout_marginTop="20dp"

        android:layout_marginBottom="20dp"

        android:layout_width="match_parent"

        android:layout_height="wrap_content">


        <ImageView

            android:layout_width="120dp"

            android:layout_height="60dp"

            android:id="@+id/img_android"

            android:layout_alignParentLeft="true"

            android:layout_alignParentTop="true"

            android:layout_marginRight="20dp"/>


        <TextView

            android:layout_marginTop="10dp"

            android:textSize="18sp"

            android:layout_width="wrap_content"

            android:layout_height="wrap_content"

            android:id="@+id/tv_android"

            android:textStyle="bold"

            android:layout_centerVertical="true"

            android:layout_toRightOf="@+id/img_android" />

    </RelativeLayout>


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

AndroidVersion.java

public class AndroidVersion {


    private String android_version_name;

    private String android_image_url;


    public String getAndroid_version_name() {

        return android_version_name;

    }


    public void setAndroid_version_name(String android_version_name) {

        this.android_version_name = android_version_name;

    }


    public String getAndroid_image_url() {

        return android_image_url;

    }


    public void setAndroid_image_url(Stringandroid_image_url) {

        this.android_image_url = android_image_url;

    }

}

Creating Adapter

public class DataAdapter extends RecyclerView.Adapter<DataAdapter.ViewHolder> {

    private ArrayList<AndroidVersion> android_versions;

    private Context context;


    public DataAdapter(Context context,ArrayList<AndroidVersion> android_versions) {

        this.context = context;

        this.android_versions = android_versions;


    }


    @Override

    public DataAdapter.ViewHolder onCreateViewHolder(ViewGroup viewGroup, int i) {

        View view = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.row_layout, viewGroup, false);

        return new ViewHolder(view);

    }


    @Override

    public void onBindViewHolder(ViewHolder viewHolder, int i) {


        viewHolder.tv_android.setText(android_versions.get(i).getAndroid_version_name());

        Picasso.with(context).load(android_versions.get(i).getAndroid_image_url()).resize(120, 60).into(viewHolder.img_android);

    }


    @Override

    public int getItemCount() {

        return android_versions.size();

    }


    public class ViewHolder extends RecyclerView.ViewHolder{

        TextView tv_android;

        ImageView img_android;

        public ViewHolder(View view) {

            super(view);


            tv_android = (TextView)view.findViewById(R.id.tv_android);

            img_android = (ImageView)view.findViewById(R.id.img_android);

        }

    }

}

In our Activity the android version names are defined in the array android_version_names. Similarly the image urls are defined in android_image_urls. We create a new AndroidVersion object and use getters and setters to set the version name and image URL. Finally we add all those objects to ArrayList.


Finally a new DataAdapter object is created and set to RecyclerView using setAdapter() method

public class MainActivity extends AppCompatActivity {

    private final String android_version_names[] = {

            "Donut",

            "Eclair",

            "Froyo",

            "Gingerbread",

            "Honeycomb",

            "Ice Cream Sandwich",

            "Jelly Bean",

            "KitKat",

            "Lollipop",

            "Marshmallow"

    };


    private final String android_image_urls[] = {

            "http://api.learn2crack.com/android/images/donut.png",

            "http://api.learn2crack.com/android/images/eclair.png",

            "http://api.learn2crack.com/android/images/froyo.png",

            "http://api.learn2crack.com/android/images/ginger.png",

            "http://api.learn2crack.com/android/images/honey.png",

            "http://api.learn2crack.com/android/images/icecream.png",

            "http://api.learn2crack.com/android/images/jellybean.png",

            "http://api.learn2crack.com/android/images/kitkat.png",

            "http://api.learn2crack.com/android/images/lollipop.png",

            "http://api.learn2crack.com/android/images/marshmallow.png"

    };


    @Override

    protected void onCreate(Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);

        setContentView(R.layout.activity_main);


        initViews();

    }


    private void initViews(){

         RecyclerView recyclerView = (RecyclerView)findViewById(R.id.card_recycler_view);

        recyclerView.setHasFixedSize(true);

        RecyclerView.LayoutManager layoutManager = new LinearLayoutManager(getApplicationContext());

        recyclerView.setLayoutManager(layoutManager);


        ArrayList androidVersions = prepareData();

        DataAdapter adapter = new DataAdapter(getApplicationContext(),androidVersions);

        recyclerView.setAdapter(adapter);


    }

    private ArrayList prepareData(){


        ArrayList android_version = new ArrayList<>();

        for(int i=0;i<android_version_names.length;i++){

            AndroidVersion androidVersion = new AndroidVersion();

            androidVersion.setAndroid_version_name(android_version_names[i]);

            androidVersion.setAndroid_image_url(android_image_urls[i]);

            android_version.add(androidVersion);

        }

        return android_version;

    }

}

Screenshot

Android Image loading in RecyclerView using Picasso