Showing posts with label recyclerview. Show all posts
Showing posts with label recyclerview. Show all posts

Thursday, 23 September 2021

Android Jetpack Compose- An easy way to RecyclerView | How to create a RecyclerView in Jetpack Compose | LazyColumn-JetPack Compose

 Hello Friends,
        Today I am going to share a my another JetPack Compose tutorial.
Here I am going to share you the creation of listview/recyclerview using 
Compose.



Creating a listview/recyclerview in Compose:
                                            Creating a listview/recyclerview in Compose is easy.
No Adapter. No View holder.


What is LazyColumn?
- A LazyColumn is a vertically scrolling list that only composes and lays out the currently visible items. It’s similar to a Recyclerview in the classic Android View system.


Download code from here
Hope this will help someone.
Enjoy Coding......................... :)

Tuesday, 19 September 2017

RecyclerView with multiple View Type | RecyclerView with different view types | View Pager inside RecyclerView

Hello Friends,
              Today I am going to share my another android tutorial, with the help
of this we can easily create a Recyclerview with multiple different types
of view .
Also this tutorial helps you to create a View pager inside RecyclerView,


























1. MainActivity.java :

package com.developer.solutions.recyclerviewwithmultipleviewtype.activity;

import android.app.Activity;
import android.content.Intent;
import android.os.Binder;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.DefaultItemAnimator;
import android.support.v7.widget.LinearLayoutCompat;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.OrientationHelper;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.Toolbar;
import android.widget.TextView;

import com.developer.solutions.recyclerviewwithmultipleviewtype.R;
import com.developer.solutions.recyclerviewwithmultipleviewtype.adapter.MultiViewTypeAdapter;
import com.developer.solutions.recyclerviewwithmultipleviewtype.model.Data;

import java.util.ArrayList;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.Unbinder;

/**
 * Created by Mukesh on 3/8/17.
 * himky02@gmail.com
 */
public class MainActivity extends AppCompatActivity {

    Activity mActivity;
    @BindView(R.id.toolbar)
    Toolbar toolbar;
    @BindView(R.id.rv)
    RecyclerView mRecyclerView;
    Unbinder mUnbinder;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        //((TextView) findViewById(R.id.tv)).setText("Welcome user");
        mUnbinder = ButterKnife.bind(this);

        ArrayList list = new ArrayList<>();
        list.add(new Data(Data.VIEW_PAGER, "Hello. This is the View Pager view type with images", 0));
        list.add(new Data(Data.IMAGE_TYPE, "A view type with Image and Textview", R.drawable.disneys_cinderella));
        list.add(new Data(Data.AUDIO_TYPE, "Hey, A view type with Button and Textview", 0));
        list.add(new Data(Data.IMAGE_TYPE, "Hi again. A view with Image and Textview", R.drawable.snow));

        MultiViewTypeAdapter adapter = new MultiViewTypeAdapter(list, this);
        final LinearLayoutManager linearLayoutManager = new LinearLayoutManager(this);
        linearLayoutManager.setOrientation(LinearLayoutManager.VERTICAL);
        mRecyclerView.setLayoutManager(linearLayoutManager);
        mRecyclerView.setItemAnimator(new DefaultItemAnimator());
        mRecyclerView.setAdapter(adapter);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
         if (mUnbinder != null) mUnbinder.unbind();
    }
}


2.MultiViewTypeAdapter.java
package com.developer.solutions.recyclerviewwithmultipleviewtype.adapter;

import android.app.Activity;
import android.content.Context;
import android.graphics.Color;
import android.os.Handler;
import android.support.v4.view.ViewPager;
import android.support.v7.widget.RecyclerView;
import android.text.Html;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.developer.solutions.recyclerviewwithmultipleviewtype.R;
import com.developer.solutions.recyclerviewwithmultipleviewtype.model.Data;

import java.util.ArrayList;

import butterknife.BindView;
import butterknife.ButterKnife;

/**
 * Created by Mukesh on 3/8/17.
 * himky02@gmail.com
 */
public class MultiViewTypeAdapter extends RecyclerView.Adapter {
    private ArrayList dataSet;
    Context mContext;
    int total_types;
    ArrayList slider_image_list;
    int page = 0;

    public static class TextTypeViewHolder extends RecyclerView.ViewHolder {
        @BindView(R.id.ll_dots)
        LinearLayout ll_dots;
        @BindView(R.id.vp_slider)
        ViewPager mvViewPager;

        public TextTypeViewHolder(View itemView) {
            super(itemView);
            ButterKnife.bind(this, itemView);
        }
    }

    public static class ImageTypeViewHolder extends RecyclerView.ViewHolder {
        @BindView(R.id.type)
        TextView tvtype;
        @BindView(R.id.img)
        ImageView iv;

        public ImageTypeViewHolder(View itemView) {
            super(itemView);
            ButterKnife.bind(this, itemView);
        }
    }

    public static class ButtonTypeViewHolder extends RecyclerView.ViewHolder {
        @BindView(R.id.type)
        TextView type;
        @BindView(R.id.btn)
        Button btn;

        public ButtonTypeViewHolder(View itemView) {
            super(itemView);
            ButterKnife.bind(this, itemView);
        }
    }

    public MultiViewTypeAdapter(ArrayList data, Context context) {
        this.dataSet = data;
        this.mContext = context;
        total_types = dataSet.size();
    }

    @Override
    public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {

        View view;
        switch (viewType) {
            case Data.VIEW_PAGER:
                view = LayoutInflater.from(parent.getContext()).inflate(R.layout.viewpager, parent, false);
                return new TextTypeViewHolder(view);
            case Data.IMAGE_TYPE:
                view = LayoutInflater.from(parent.getContext()).inflate(R.layout.item_image_type, parent, false);
                return new ImageTypeViewHolder(view);
            case Data.AUDIO_TYPE:
                view = LayoutInflater.from(parent.getContext()).inflate(R.layout.item_button_type, parent, false);
                return new ButtonTypeViewHolder(view);
        }
        return null;


    }


    @Override
    public int getItemViewType(int position) {

        switch (dataSet.get(position).type) {
            case 0:
                return Data.VIEW_PAGER;
            case 1:
                return Data.IMAGE_TYPE;
            case 2:
                return Data.AUDIO_TYPE;
            default:
                return -1;
        }
    }

    @Override
    public void onBindViewHolder(final RecyclerView.ViewHolder holder, final int listPosition) {

        Data object = dataSet.get(listPosition);
        if (object != null) {
            switch (object.type) {
                case Data.VIEW_PAGER:
                    //((TextTypeViewHolder) holder).type.setText(object.text);
                    slider_image_list = new ArrayList<>();

                    //Add few items to slider_image_list ,this should contain url of images which should be displayed in slider
                    // here i am adding few sample image links, you can add your own

                    slider_image_list.add("http://cdn.collider.com/wp-content/uploads/avengers-movie-banner-scarlett-johansson-jeremy-renner.jpg");
                    slider_image_list.add("http://www.officialterridwyer.com/wp-content/uploads/2015/04/Disneys-Cinderella-2015-Movie-Banner.jpg");
                    slider_image_list.add("http://igmedia.blob.core.windows.net/igmedia/hindi/gallery/movies/raabta/main1.jpg");
                    slider_image_list.add("http://fantoosy.com/wp-content/uploads/2015/11/tamasha.jpg");
                    final SliderPagerAdapter sliderPagerAdapter = new SliderPagerAdapter((Activity) mContext, slider_image_list);
                    ((TextTypeViewHolder) holder).mvViewPager.setAdapter(sliderPagerAdapter);

                    ((TextTypeViewHolder) holder).mvViewPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
                        @Override
                        public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

                        }

                        @Override
                        public void onPageSelected(int position) {
                            addBottomDots(position, ((TextTypeViewHolder) holder).ll_dots);
                            page = position;
                        }

                        @Override
                        public void onPageScrollStateChanged(int state) {

                        }
                    });
                    addBottomDots(0, ((TextTypeViewHolder) holder).ll_dots);
                    final Handler h = new Handler();
                    h.postDelayed(new Runnable() {
                        @Override
                        public void run() {
                            if (sliderPagerAdapter.getCount() == page) {
                                page = 0;
                            } else {
                                page++;
                            }
                            ((TextTypeViewHolder) holder).mvViewPager.setCurrentItem(page);
                            h.postDelayed(this, 2000);
                        }
                    }, 1000);

                    break;
                case Data.IMAGE_TYPE:
                    ((ImageTypeViewHolder) holder).tvtype.setText(object.text);
                    ((ImageTypeViewHolder) holder).iv.setImageResource(object.data);
                    break;
                case Data.AUDIO_TYPE:
                    ((ButtonTypeViewHolder) holder).type.setText(object.text);
                    ((ButtonTypeViewHolder) holder).btn.setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View view) {
                            Toast.makeText(mContext, "You clicked!!!", Toast.LENGTH_SHORT).show();
                        }
                    });
                    break;
            }
        }

    }

    @Override
    public int getItemCount() {
        return dataSet.size();
    }

    //showing dots on screen
    private void addBottomDots(int currentPage, LinearLayout ll_dots) {
        TextView[] dots = new TextView[slider_image_list.size()];
        ll_dots.removeAllViews();
        for (int i = 0; i < dots.length; i++) {
            dots[i] = new TextView(mContext);
            dots[i].setText(Html.fromHtml("•"));
            dots[i].setTextSize(35);
            dots[i].setTextColor(Color.parseColor("#343434"));
            ll_dots.addView(dots[i]);
        }

        if (dots.length > 0)
            dots[currentPage].setTextColor(Color.parseColor("#A2A2A2"));
    }

}
Download the code from here

Hope this will helps some one.
Enjoy Coding....

Monday, 18 January 2016

Android RecyclerView and CardView tutorial | Android RecyclerView and CardView widgets | Android RecyclerView and CardView with backward compatibility

Hello Friends,
         Today, I am going to share my another post on Android RecyclerView and CardView.
This widgets come in android  latest release i.e Lollipop, Android 5.0 and API Level 21.
We can also add support on lower devices above API Level 7 by adding support library.
For creating complex Listview we need RecyclerView  and CardView.



Android RecyclerView: The advance version of Listview is RecyclerView, It is more
                                        advance and flexible. RecyclerView uses Layout manager for
managing position of item inside the recycler view. Recycler view provides three
built in Layout manager :

1. LinearLayoutManager : shows items in a vertical or horizontal scrolling list.
2. GridLayoutManager: shows items in a grid.
3. StaggeredGridLayoutManager: shows items in a staggered grid.

For more check this Link


CardView Widget:  It help us in showing information inside cards that have a consistent
                                  look across the platform. CardView widgets can have shadows and
                                  rounded corners.
 Note:
       1. To create a card with a shadow, use the card_view:cardElevation attribute. 
       2. To set the corner radius in your layouts, use the card_view:cardCornerRadius
           attribute.
      3. To set the corner radius in your code, use the CardView.setRadius method.
      4. To set the background color of a card, use the card_view:cardBackgroundColor
            attribute.


Here is Sample Code:

1. MainActivity.java

package solutions.developer.android.com.recyclerview;

import android.app.Activity;
import android.database.Cursor;
import android.os.AsyncTask;
import android.os.Bundle;
import android.provider.MediaStore;
import android.support.v7.widget.DefaultItemAnimator;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;

import java.util.ArrayList;
import java.util.List;


/**
 * Created by Mukesh on 12/20/2015.
 */

public class MainActivity extends Activity {

    /**
     * Cursor used to access the results from querying for images
     * on the SD card.
     */
    private Cursor cursor;
    /*
     * Column index for the Thumbnails Image IDs.
     */
    private int columnIndex;
    private static final String TAG = "RecyclerViewExample";

    private List mediaList = new ArrayList();

    private RecyclerView mRecyclerView;

    private MediaRVAdapter adapter;

    String type = "";

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

        /* Initialize recyclerview */
        mRecyclerView = (RecyclerView) findViewById(R.id.list);
        mRecyclerView.setLayoutManager(new LinearLayoutManager(this));
        mRecyclerView.setItemAnimator(new DefaultItemAnimator());

        type = "audio";
        new MediaAsyncTask().execute(type);

    }

    private void parseAllAudio(String type) {
        try {
          String TAG = "Audio";
          Cursor cur = getContentResolver().query(
                 MediaStore.Audio.Media.EXTERNAL_CONTENT_URI, null, null, null,
                  null);

          if (cur == null) {
              // Query failed...
              Log.e(TAG, "Failed to retrieve music: cursor is null :-(");
          } else if (!cur.moveToFirst()) {
             // Nothing to query. There is no music on the device. How boring.
              Log.e(TAG, "Failed to move cursor to first row (no query results).");
          } else {
              Log.i(TAG, "Listing...");
              // retrieve the indices of the columns where the ID,
              //title, etc. of the song are
              // add each song to mItems
             do {
                 int artistColumn = cur.getColumnIndex(MediaStore.Audio.Media.ARTIST);
                 int titleColumn = cur.getColumnIndex(MediaStore.Audio.Media.TITLE);
                 int albumColumn = cur.getColumnIndex(MediaStore.Audio.Media.ALBUM);
                 int durationColumn = cur.getColumnIndex(MediaStore.Audio.Media.DURATION);
                 int idColumn = cur.getColumnIndex(MediaStore.Audio.Media._ID);
              int filePathIndex = cur.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
                 Log.i(TAG, "Title column index: " + String.valueOf(titleColumn));
                 Log.i(TAG, "ID column index: " + String.valueOf(titleColumn));

                 Log.i("Final ", "ID: " + cur.getString(idColumn) + " Title: "
                 + cur.getString(titleColumn) + "Path: " +
                   cur.getString(filePathIndex));
                 MediaFileInfo audio = new MediaFileInfo();
                 audio.setFileName(cur.getString(titleColumn));
                 audio.setFilePath(cur.getString(filePathIndex));
                 audio.setFileType(type);
                 mediaList.add(audio);

              } while (cur.moveToNext());
          }

      } catch (Exception e) {
            e.printStackTrace();
      }
  }

  public class MediaAsyncTask extends AsyncTask {

      @Overrid
      protected void onPreExecute() {
        //setProgressBarIndeterminateVisibility(true);
      }

     @Override
     protected Integer doInBackground(String... params) {
         Integer result = 0;
         String type = params[0];
         try {
             mediaList = new ArrayList();
              if (type.equalsIgnoreCase("audio")) {
                   parseAllAudio(type);
                   result = 1;
              }
        } catch (Exception e) {
              e.printStackTrace();
              result = 0;
        }
       return result; //"Failed to fetch data!";
   }
    @Override
    protected void onPostExecute(Integer result) {

      // setProgressBarIndeterminateVisibility(false);
      /* Download complete. Lets update UI */
      if (result == 1) {
          adapter = new MediaRVAdapter(MainActivity.this, mediaList);
          mRecyclerView.setAdapter(adapter);
      } else {
          Log.e(TAG, "Failed to fetch data!");
      }
   }
 }
} 

2. MediaRVAdapter.java

package solutions.developer.android.com.recyclerview;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.media.MediaMetadataRetriever;
import android.media.ThumbnailUtils;
import android.net.Uri;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;

import java.io.File;
import java.util.List;

/**
 * Created by Mukesh on 12/20/2015.
 */
public class MediaRVAdapter extends RecyclerView.Adapter {


    private List itemList;

    private Context mContext;

    public MediaRVAdapter(Context context, List itemList) {
        this.itemList = itemList;
        this.mContext = context;
    }

    @Override
    public MediaListRowHolder onCreateViewHolder(ViewGroup viewGroup, int i) {
        View v = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.item, null);
        MediaListRowHolder mh = new MediaListRowHolder(v);

        return mh;
    }

    @Override
    public void onBindViewHolder(MediaListRowHolder mediaListRowHolder, int i) {
        try {
            MediaFileInfo item = itemList.get(i);
            mediaListRowHolder.title.setText(item.getFileName());
            Uri uri = Uri.fromFile(new File(item.getFilePath()));
            if (item.getFileType().equalsIgnoreCase("audio")) {
                MediaMetadataRetriever mmr = new MediaMetadataRetriever();
                mmr.setDataSource(item.getFilePath());
                try {
                    if (mmr != null) {
                        byte[] art = mmr.getEmbeddedPicture();
                        if (art != null && art.length > 0) {
                            Bitmap bmp = BitmapFactory.decodeByteArray(art, 0, art.length);
                            if (bmp != null) {
                                bmp = ThumbnailUtils.extractThumbnail(bmp, 80, 50);
                                mediaListRowHolder.thumbnail.setImageBitmap(bmp);
                            }
                        }
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    public int getItemCount() {
        return (null != itemList ? itemList.size() : 0);
    }

    public class MediaListRowHolder extends RecyclerView.ViewHolder {
        protected ImageView thumbnail;
        protected TextView title;

        public MediaListRowHolder(View view) {
            super(view);
            this.thumbnail = (ImageView) view.findViewById(R.id.image);
            this.title = (TextView) view.findViewById(R.id.name);
        }
    }
} 


Download Complete Code from here

Hope this will help some one.....
Enjoy coding.......
Cheers  :)

 

Copyright @ 2013 Android Developer Blog.