Monday, November 28, 2016

Observable Recyclerview

Observable Recyclerview


First of all we need to add below dependencies into gradle

compile 'com.android.support:design:25.0.1'
compile'com.android.support:recyclerview-v7:25.0.1'

Now we have to create adapter_simple_recyclerview.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:layout_height="wrap_content">

    <TextView        
     android:id="@+id/tvName"        
     android:layout_width="wrap_content"        
     android:layout_height="wrap_content"        
     android:padding="10dp"/>

</LinearLayout>


Here is activity_main.xml


<android.support.design.widget.CoordinatorLayout 
xmlns:android="http://schemas.android.com/apk/res/android"   
xmlns:app="http://schemas.android.com/apk/res-auto"    
android:layout_width="match_parent"    
android:layout_height="match_parent">

<!--add Appbar layout-->


    <android.support.design.widget.AppBarLayout        
      android:layout_width="match_parent"        
      android:layout_height="wrap_content">


        <android.support.v7.widget.Toolbar            
         android:id="@+id/toolbar"            
         android:layout_width="match_parent"            
         android:layout_height="?attr/actionBarSize"            
         android:background="?attr/colorPrimary"            
         app:layout_scrollFlags="scroll|enterAlways"            
         app:popupTheme="@style/ThemeOverlay.AppCompat.Light"            
         app:theme="@style/ThemeOverlay.AppCompat.Dark.ActionBar" />

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



    <!--add NestedScrollView-->

    <android.support.v4.widget.NestedScrollView        
     android:layout_width="match_parent"        
     android:layout_height="match_parent"        
     android:fillViewport="true"        
     app:layout_behavior="@string/appbar_scrolling_view_behavior">
        
      <!--Linear layout to add custom layout-->

        <LinearLayout            
         android:layout_width="match_parent"            
         android:layout_height="match_parent"            
         android:orientation="vertical">

          <!--add textview-->
            <TextView                
              android:layout_width="wrap_content"                
              android:layout_height="wrap_content"                
              android:text="This is Heading textview."                
              android:layout_gravity="center"                
              android:textSize="20sp"                
              android:textColor="#666" />

            <!--add Recyclerview-->
            <android.support.v7.widget.RecyclerView                
             android:id="@+id/rvSimple"                
             android:layout_width="match_parent"                
             android:layout_height="wrap_content"                
             android:scrollbars="vertical" />

        </LinearLayout>
    </android.support.v4.widget.NestedScrollView>

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

Add divider.xml 

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

    <solid android:color="#cccccc"/>
    
     <size android:width="1dp"        
     android:height="1dp" />

</shape>



Below is DividerItemDecoration class.

public class DividerItemDecoration extends RecyclerView.ItemDecoration  {

    private Drawable mDivider;
    private boolean mShowFirstDivider = false;
    private boolean mShowLastDivider = false;


    public DividerItemDecoration(Context context, AttributeSet attrs) {
        final TypedArray a = context
                .obtainStyledAttributes(attrs, new int[]{android.R.attr.listDivider});
        mDivider = a.getDrawable(0);
        a.recycle();
    }

    public DividerItemDecoration(Context context, AttributeSet attrs, boolean showFirstDivider,
                                 boolean showLastDivider) {
        this(context, attrs);
        mShowFirstDivider = showFirstDivider;
        mShowLastDivider = showLastDivider;
    }

    public DividerItemDecoration(Drawable divider) {
        mDivider = divider;
    }

    public DividerItemDecoration(Drawable divider, boolean showFirstDivider,
                                 boolean showLastDivider) {
        this(divider);
        mShowFirstDivider = showFirstDivider;
        mShowLastDivider = showLastDivider;
    }

    @Override    public void getItemOffsets(Rect outRect, View view, RecyclerView parent,
                               RecyclerView.State state) {
        super.getItemOffsets(outRect, view, parent, state);
        if (mDivider == null) {
            return;
        }
        if (parent.getChildPosition(view) < 1) {
            return;
        }

        if (getOrientation(parent) == LinearLayoutManager.VERTICAL) {
            outRect.top = mDivider.getIntrinsicHeight();
        } else {
            outRect.left = mDivider.getIntrinsicWidth();
        }
    }

    @Override    public void onDrawOver(Canvas c, RecyclerView parent, RecyclerView.State state) {
        if (mDivider == null) {
            super.onDrawOver(c, parent, state);
            return;
        }

        // Initialization needed to avoid compiler warning

        int left = 0, right = 0, top = 0, bottom = 0, size;
        int orientation = getOrientation(parent);
        int childCount = parent.getChildCount();

        if (orientation == LinearLayoutManager.VERTICAL) {
            size = mDivider.getIntrinsicHeight();
            left = parent.getPaddingLeft();
            right = parent.getWidth() - parent.getPaddingRight();
        } else { //horizontal            size = mDivider.getIntrinsicWidth();
            top = parent.getPaddingTop();
            bottom = parent.getHeight() - parent.getPaddingBottom();
        }

        for (int i = mShowFirstDivider ? 0 : 1; i < childCount; i++) {
            View child = parent.getChildAt(i);
            RecyclerView.LayoutParams params = (RecyclerView.LayoutParams) child.getLayoutParams();

            if (orientation == LinearLayoutManager.VERTICAL) {
                top = child.getTop() - params.topMargin;
                bottom = top + size;
            } else { //horizontal                left = child.getLeft() - params.leftMargin;
                right = left + size;
            }
            mDivider.setBounds(left, top, right, bottom);
            mDivider.draw(c);
        }

        // show last divider        if (mShowLastDivider && childCount > 0) {
            View child = parent.getChildAt(childCount - 1);
            RecyclerView.LayoutParams params = (RecyclerView.LayoutParams) child.getLayoutParams();
            if (orientation == LinearLayoutManager.VERTICAL) {
                top = child.getBottom() + params.bottomMargin;
                bottom = top + size;
            } else { // horizontal                left = child.getRight() + params.rightMargin;
                right = left + size;
            }
            mDivider.setBounds(left, top, right, bottom);
            mDivider.draw(c);
        }
    }

    private int getOrientation(RecyclerView parent) {
        if (parent.getLayoutManager() instanceof LinearLayoutManager) {
            LinearLayoutManager layoutManager = (LinearLayoutManager) parent.getLayoutManager();
            return layoutManager.getOrientation();
        } else {
            throw new IllegalStateException(
                    "DividerItemDecoration can only be used with a LinearLayoutManager.");
        }
    }

}

Below is studentModel class.

public class StudentModel implements Serializable {

    private String strName;

    public String getStrName() {
        return strName;
    }

    public void setStrName(String strName) {
        this.strName = strName;
    }
}

Here is SimpleRecyclerAdapter.

public class SimpleRecyclerAdapter extends RecyclerView.Adapter<SimpleRecyclerAdapter.SimpleViewHolder> {

    private ArrayList<StudentModel> alStudent;

    public SimpleRecyclerAdapter(ArrayList<StudentModel> alStudent) {

        this.alStudent = alStudent;
        Log.e("Arraylist size ","In Adapter ===> "+alStudent.size());
    }

    @Override    public SimpleViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        View itemView = LayoutInflater.from(parent.getContext()).inflate(R.layout.adapter_simple_recyclerview, parent, false);
        return new SimpleViewHolder(itemView);
    }

    @Override    public void onBindViewHolder(SimpleViewHolder holder, int position) {
        holder.tvName.setText(alStudent.get(position).getStrName());
    }


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

    public class SimpleViewHolder extends RecyclerView.ViewHolder {

        private TextView tvName;

        public SimpleViewHolder(View itemView) {
            super(itemView);

            tvName = (TextView) itemView.findViewById(R.id.tvName);
        }
    }

}


Here is my MainActivity.

public class MainActivity extends AppCompatActivity {

    private ArrayList<StudentModel> alStudent;
    private RecyclerView rvSimple;
    private SimpleRecyclerAdapter simpleRecyclerAdapter;
    private StudentModel model;
    private int s=0;
    private LinearLayoutManager linearLayoutManager;


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

        alStudent = new ArrayList<>();

        Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);
        ActionBar actionBar = getSupportActionBar();
        actionBar.setDisplayHomeAsUpEnabled(true);


        getId();
        loadArrayList();
        setRecycler();

    }

    private void setRecycler() {
        try {
            linearLayoutManager = new LinearLayoutManager(MainActivity.this);
            rvSimple.setLayoutManager(linearLayoutManager);

            //add devider to recycleview.

            rvSimple.addItemDecoration(new DividerItemDecoration(getResources().getDrawable(R.drawable.divider)));

            // adapter initialized.

            simpleRecyclerAdapter = new SimpleRecyclerAdapter(alStudent);
            rvSimple.setAdapter(simpleRecyclerAdapter);

            simpleRecyclerAdapter.notifyDataSetChanged();
        } catch (Resources.NotFoundException e) {
            e.printStackTrace();
        }
    }

    private void loadArrayList() {
        try {
            for (int i = 0; i <= 50; i++) {

                model = new StudentModel();
                model.setStrName("Student "+s);
                alStudent.add(model);
                s++;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private void getId() {
        try {
            rvSimple = (RecyclerView)findViewById(R.id.rvSimple);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

No comments:

Post a Comment