Generic Adapter


Source link: https://github.com/mohanmanu484/Generic-Adapter

Generic-Adapter

One recycler view adapter for all your project

1.enable databinding in your app gradle

 dataBinding{

enabled true  
}
 
  1. Add dependency

      compile ('com.mohanmanu.genericadapter:genericadapter:1.0'){
    
     exclude group: 'com.android.support'
    
    }
     
  2. Add attributes for your recycler view

     <data>
    
     <variable
    
     name="list"
    
     type="android.databinding.ObservableList" />  </data>
     <LinearLayout
    
    android:layout_width="match_parent"
    
    android:layout_height="match_parent"
    
    android:orientation="vertical">
    
     <android.support.v7.widget.RecyclerView
    
     android:layout_width="match_parent"
    
     android:layout_height="match_parent"
    
     app:genericLayout="@{
    @layout/adapter_single_view_type
    }
    "
    
     app:listItem="@{
    list
    }
    " />
    </LinearLayout> 

provide observable list from your fragment or activity or viewmodel

say you are having fragment called SingleViewTypeFragment

  public class SingleViewTypeFragment extends Fragment {

public ObservableList<String> observableList=new ObservableArrayList<>();

  @Nullable
@Override
public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, Bundle savedInstanceState) {

  FragmentSingleViewtypeBinding fragmentSingleViewtypeBinding=DataBindingUtil.inflate(inflater,R.layout.fragment_single_viewtype,container,false);

 fragmentSingleViewtypeBinding.setList(observableList);

 observableList.add("test string");

 return fragmentSingleViewtypeBinding.getRoot();

}

}
 
  1. write adapter items layout

     <variable
    
    name="item"
    
    type="String" /> 

     <TextView
    
    android:layout_width="match_parent"
    
    android:layout_height="wrap_content"
    
    android:padding="@dimen/dimen_16"
    
    android:text="@{
    item
    }
    "
    
    tools:text="single view type" /> 

thats it you are done no need to write adapter everytime you create a new list

  1. To handle Onclick events add one more attribute to recycler view

example

 <layout xmlns:android="http://schemas.android.com/apk/res/android"
 xmlns:tools="http://schemas.android.com/tools"
 xmlns:app="http://schemas.android.com/apk/res-auto">
  <data>

  <variable

name="list"

type="android.databinding.ObservableList"/>

  <variable

name="viewListener"

type="com.mohang.genericadapter.ViewListener"/>
 </data>
  <LinearLayout

  android:orientation="vertical" android:layout_width="match_parent"

  android:layout_height="match_parent">

  <android.support.v7.widget.RecyclerView

 app:viewListener="@{
viewListener
}
"

app:genericLayout="@{
@layout/adapter_single_view_type
}
"

app:listItem="@{
list
}
"

android:layout_width="match_parent"

android:layout_height="match_parent"

/>
  </LinearLayout>  </layout> 

in the above code snippet it is expecting a variable of type viewListener so provide the implementation for the viewListener in your activity or fragment or viewModel

public class ViewClickListenerFragment extends Fragment {

 public ObservableList observableList=new ObservableArrayList();

 @Nullable
@Override
public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, Bundle savedInstanceState) {

  FragmentViewListenerBinding fragmentSingleViewtypeBinding= DataBindingUtil.inflate(inflater,R.layout.fragment_view_listener,container,false);

 fragmentSingleViewtypeBinding.setList(observableList);

 observableList.addAll(DataSource.getListOfNUmbers());

 fragmentSingleViewtypeBinding.setViewListener(viewListener);

 return fragmentSingleViewtypeBinding.getRoot();

}

 public ViewListener viewListener=new ViewListener() {

 @Override

 public void onClick(View v, int pos, Object object) {

Toast.makeText(getActivity(), "item @ pos "+pos+" is "+((String)object), Toast.LENGTH_SHORT).show();

 
}

}
; 
}
 

Thats how we can handle onClick event on an adapter

  1. So next how to handle situation when I'm having multiple viewTypes? so that can also be handled by adding one more attribute called viewTypeListener
<variable

  name="viewTypeHandler"

  type="com.mohang.genericadapter.ViewTypeHandler"/> 

provide variable of type ViewTypeHandler in your recyclerview

then write the ViewType handler in your view , based on the position or object that you are getting you can return different layout that you want to inflate

  ViewTypeHandler viewTypeHandler=new ViewTypeHandler() {

 @Override

 public int getViewType(int pos, Object item) {

  if(item instanceof Car){

return R.layout.adapter_car_view_type;

  
}

  return R.layout.adapter_bus_view_type;

 
}

}
; 

and add it onto recycler view

<android.support.v7.widget.RecyclerView

  android:layout_width="match_parent"

  android:layout_height="match_parent"

  app:viewTypeHandler="@{
viewTypeHandler
}
"

  app:listItem="@{
list
}
" /> 
  1. for more complex cases like gridlayout adapter ,and handling onclicks for different views on a same layout please refer to the examples given

  2. Rules of adapter items

<data>

<variable

 name="item"

 type="String" />

  <variable

 name="pos"

 type="Integer" />

  <variable

 name="actionHandler"

 type="your handler class which imlements ActionHandler" />  </data> 

your adapter item should always use the same variable to work

find the apk here https://play.google.com/store/apps/details?id=com.mohang.genericadapterexample

Resources

Topics


2D Engines   3D Engines   9-Patch   Action Bars   Activities   ADB   Advertisements   Analytics   Animations   ANR   AOP   API   APK   APT   Architecture   Audio   Autocomplete   Background Processing   Backward Compatibility   Badges   Bar Codes   Benchmarking   Bitmaps   Bluetooth   Blur Effects   Bread Crumbs   BRMS   Browser Extensions   Build Systems   Bundles   Buttons   Caching   Camera   Canvas   Cards   Carousels   Changelog   Checkboxes   Cloud Storages   Color Analysis   Color Pickers   Colors   Comet/Push   Compass Sensors   Conferences   Content Providers   Continuous Integration   Crash Reports   Credit Cards   Credits   CSV   Curl/Flip   Data Binding   Data Generators   Data Structures   Database   Database Browsers   Date &   Debugging   Decompilers   Deep Links   Dependency Injections   Design   Design Patterns   Dex   Dialogs   Distributed Computing   Distribution Platforms   Download Managers   Drawables   Emoji   Emulators   EPUB   Equalizers &   Event Buses   Exception Handling   Face Recognition   Feedback &   File System   File/Directory   Fingerprint   Floating Action   Fonts   Forms   Fragments   FRP   FSM   Functional Programming   Gamepads   Games   Geocaching   Gestures   GIF   Glow Pad   Gradle Plugins   Graphics   Grid Views   Highlighting   HTML   HTTP Mocking   Icons   IDE   IDE Plugins   Image Croppers   Image Loaders   Image Pickers   Image Processing   Image Views   Instrumentation   Intents   Job Schedulers   JSON   Keyboard   Kotlin   Layouts   Library Demos   List View   List Views   Localization   Location   Lock Patterns   Logcat   Logging   Mails   Maps   Markdown   Mathematics   Maven Plugins   MBaaS   Media   Menus   Messaging   MIME   Mobile Web   Native Image   Navigation   NDK   Networking   NFC   NoSQL   Number Pickers   OAuth   Object Mocking   OCR Engines   OpenGL   ORM   Other Pickers   Parallax List   Parcelables   Particle Systems   Password Inputs   PDF   Permissions   Physics Engines   Platforms   Plugin Frameworks   Preferences   Progress Indicators   ProGuard   Properties   Protocol Buffer   Pull To   Purchases   Push/Pull   QR Codes   Quick Return   Radio Buttons   Range Bars   Ratings   Recycler Views   Resources   REST   Ripple Effects   RSS   Screenshots   Scripting   Scroll Views   SDK   Search Inputs   Security   Sensors   Services   Showcase Views   Signatures   Sliding Panels   Snackbars   SOAP   Social Networks   Spannable   Spinners   Splash Screens   SSH   Static Analysis   Status Bars   Styling   SVG   System   Tags   Task Managers   TDD &   Template Engines   Testing   Testing Tools   Text Formatting   Text Views   Text Watchers   Text-to   Toasts   Toolkits For   Tools   Tooltips   Trainings   TV   Twitter   Updaters   USB   User Stories   Utils   Validation   Video   View Adapters   View Pagers   Views   Watch Face   Wearable Data   Wearables   Weather   Web Tools   Web Views   WebRTC   WebSockets   Wheel Widgets   Wi-Fi   Widgets   Windows   Wizards   XML   XMPP   YAML   ZIP Codes