How to implement RecyclerView with CardView rows in a Fragment with TabLayout
Here is a simple example using a TabLayout and a RecyclerView with a CardView in each row.
First, MainActivity, which sets up the ViewPager and TabLayout:
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
// Get the ViewPager and set it's PagerAdapter so that it can display items
ViewPager viewPager = (ViewPager) findViewById(R.id.viewpager);
PagerAdapter pagerAdapter =
new PagerAdapter(getSupportFragmentManager(), MainActivity.this);
viewPager.setAdapter(pagerAdapter);
// Give the TabLayout the ViewPager
TabLayout tabLayout = (TabLayout) findViewById(R.id.tab_layout);
tabLayout.setupWithViewPager(viewPager);
// Iterate over all tabs and set the custom view
for (int i = 0; i < tabLayout.getTabCount(); i++) {
TabLayout.Tab tab = tabLayout.getTabAt(i);
tab.setCustomView(pagerAdapter.getTabView(i));
}
}
@Override
public void onResume() {
super.onResume();
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
class PagerAdapter extends FragmentPagerAdapter {
String tabTitles[] = new String[] { "Tab One", "Tab Two", "Tab Three" };
Context context;
public PagerAdapter(FragmentManager fm, Context context) {
super(fm);
this.context = context;
}
@Override
public int getCount() {
return tabTitles.length;
}
@Override
public Fragment getItem(int position) {
switch (position) {
case 0:
return new BlankFragment();
case 1:
return new BlankFragment();
case 2:
return new BlankFragment();
}
return null;
}
@Override
public CharSequence getPageTitle(int position) {
// Generate title based on item position
return tabTitles[position];
}
public View getTabView(int position) {
View tab = LayoutInflater.from(MainActivity.this).inflate(R.layout.custom_tab, null);
TextView tv = (TextView) tab.findViewById(R.id.custom_text);
tv.setText(tabTitles[position]);
return tab;
}
}
}
activity_main.xml:
<RelativeLayout
android:id="@+id/main_layout"
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=".MainActivity">
<android.support.v7.widget.Toolbar
android:id="@+id/toolbar"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:background="?attr/colorPrimary"
android:elevation="6dp"
android:minHeight="?attr/actionBarSize"
android:theme="@style/ThemeOverlay.AppCompat.Dark.ActionBar"
app:popupTheme="@style/ThemeOverlay.AppCompat.Light"
/>
<android.support.design.widget.TabLayout
android:id="@+id/tab_layout"
app:tabMode="fixed"
android:layout_below="@+id/toolbar"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="?attr/colorPrimary"
android:elevation="6dp"
app:tabTextColor="#d3d3d3"
app:tabSelectedTextColor="#ffffff"
app:tabIndicatorColor="#ff00ff"
android:minHeight="?attr/actionBarSize"
/>
<android.support.v4.view.ViewPager
android:id="@+id/viewpager"
android:layout_below="@+id/tab_layout"
android:layout_width="match_parent"
android:layout_height="wrap_content"
/>
</RelativeLayout>
custom_tab.xml for each Tab in the TabLayout:
<?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="match_parent">
<TextView
android:id="@+id/custom_text"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="?attr/selectableItemBackground"
android:gravity="center"
android:textSize="16dip"
android:textColor="#ffffff"
android:singleLine="true"
/>
</LinearLayout>
Here is the BlankFragment class, which uses a RecyclerView to show a list:
import android.support.v4.app.Fragment;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;;
public class BlankFragment extends Fragment {
public BlankFragment() {
// Required empty public constructor
}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View rootView = inflater.inflate(R.layout.fragment_blank, container, false);
RecyclerView rv = (RecyclerView) rootView.findViewById(R.id.rv_recycler_view);
rv.setHasFixedSize(true);
MyAdapter adapter = new MyAdapter(new String[]{"test one", "test two", "test three", "test four", "test five" , "test six" , "test seven"});
rv.setAdapter(adapter);
LinearLayoutManager llm = new LinearLayoutManager(getActivity());
rv.setLayoutManager(llm);
return rootView;
}
}
fragment_blank.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="match_parent">
<android.support.v7.widget.RecyclerView
android:id="@+id/rv_recycler_view"
android:layout_width="match_parent"
android:layout_height="match_parent" >
</android.support.v7.widget.RecyclerView>
</RelativeLayout>
card_item.xml for the RecyclerView list:
<?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="68dp" >
<android.support.v7.widget.CardView
android:id="@+id/card_view"
xmlns:card_view="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_margin="10dp"
android:layout_height="62dp"
card_view:cardCornerRadius="4dp"
card_view:elevation="14dp">
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="match_parent">
<ImageView
android:id="@+id/iv_image"
android:layout_height="wrap_content"
android:layout_width="wrap_content"
android:src="@drawable/abc_btn_radio_material">
</ImageView>
<TextView
android:id="@+id/tv_text"
android:layout_toRightOf ="@+id/iv_image"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:gravity="center" >
</TextView>
<TextView
android:id="@+id/tv_blah"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="blah blah blah......"
android:layout_below="@+id/tv_text"
android:layout_toRightOf="@+id/iv_image"
android:layout_toEndOf="@+id/iv_image">
</TextView>
</RelativeLayout>
</android.support.v7.widget.CardView>
</RelativeLayout>
MyAdapter class for the RecyclerView, this is very basic and just sets the text in one of the TextViews:
import android.support.v7.widget.CardView;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
public class MyAdapter extends RecyclerView.Adapter<MyAdapter.MyViewHolder> {
private String[] mDataset;
// Provide a reference to the views for each data item
// Complex data items may need more than one view per item, and
// you provide access to all the views for a data item in a view holder
public static class MyViewHolder extends RecyclerView.ViewHolder {
public CardView mCardView;
public TextView mTextView;
public MyViewHolder(View v) {
super(v);
mCardView = (CardView) v.findViewById(R.id.card_view);
mTextView = (TextView) v.findViewById(R.id.tv_text);
}
}
// Provide a suitable constructor (depends on the kind of dataset)
public MyAdapter(String[] myDataset) {
mDataset = myDataset;
}
// Create new views (invoked by the layout manager)
@Override
public MyAdapter.MyViewHolder onCreateViewHolder(ViewGroup parent,
int viewType) {
// create a new view
View v = LayoutInflater.from(parent.getContext())
.inflate(R.layout.card_item, parent, false);
// set the view's size, margins, paddings and layout parameters
MyViewHolder vh = new MyViewHolder(v);
return vh;
}
@Override
public void onBindViewHolder(MyViewHolder holder, final int position) {
holder.mTextView.setText(mDataset[position]);
holder.mCardView.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
String currentValue = mDataset[position];
Log.d("CardView", "CardView Clicked: " + currentValue);
}
});
}
@Override
public int getItemCount() {
return mDataset.length;
}
}
Gradle dependencies used:
dependencies {
compile fileTree(dir: 'libs', include: ['*.jar'])
compile 'com.android.support:appcompat-v7:23.0.1'
compile 'com.android.support:design:23.0.1'
compile 'com.android.support:cardview-v7:23.0.1'
compile 'com.android.support:recyclerview-v7:23.0.1'
}
Here is the result:
implement recyclerview with tablayout inside fragment
If you want to use Nested fragment
than
Use getChildFragmentManager()
instead of getSupportFragmentManager()
Use this
final AddPagerAdapter adapter = new AddPagerAdapter(getChildFragmentManager(), tabLayout.getTabCount());
Instead of this
final AddPagerAdapter adapter = new AddPagerAdapter(getActivity().getSupportFragmentManager(), tabLayout.getTabCount());
EDIT notifyDataSetChanged()
in your getAdd()
after adding data in your list like below code
try this
addRecyclerViewadapter.notifyDataSetChanged();
CODE
private List<Add> getAdd() {
String tag_headers_req = "req_apikey";
JsonObjectRequest jsonObjRequest = new JsonObjectRequest(Request.Method.GET, Constant.URL_GETADD, null,
new Response.Listener<JSONObject>() {
@Override
public void onResponse(JSONObject response) {
Log.d("onResponse: ", response.toString());
try {
boolean error = response.getBoolean("error");
if (!error){
JSONArray jsonArr = response.getJSONArray("transaksi");
for (int i = 0; i < jsonArr.length(); i++){
JSONObject allObj = jsonArr.getJSONObject(i);
Add add = new Add();
add.setTitleAdd(allObj.getString("title"));
add.setPreviewAdd(allObj.getString("deskripsi"));
add.setTanggalAdd(allObj.getString("tanggal"));
add.setImg_logoAdd(allObj.getString("img_logo"));
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putString("title", add.getTitleAdd());
editor.putString("deskripsi", add.getPreviewAdd());
editor.putString("tanggal", add.getTanggalAdd());
editor.putString("img_logo", add.getImg_logoAdd());
editor.commit();
addList.add(add);
}
// add here notifyDataSetChanged();
addRecyclerViewadapter.notifyDataSetChanged();
} else {
Toast.makeText(getContext(), response.getString("message"), Toast.LENGTH_SHORT).show();
}
} catch (JSONException e) {
e.printStackTrace();
Log.d(TAG, "onResponse: " + e.getMessage());
}
}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
VolleyLog.d("Error: " + error.getMessage());
if (error instanceof TimeoutError || error instanceof NoConnectionError || error instanceof NetworkError){
Toast.makeText(getContext(), "Please check your connection!", Toast.LENGTH_SHORT).show();
}
}
})
{
@Override
public String getBodyContentType() {
return "application/x-www-form-urlencoded";
}
@Override
public Map<String, String> getHeaders() throws AuthFailureError {
Map<String, String> headers = new HashMap<>();
sharedPreferences = getActivity().getSharedPreferences("data", Context.MODE_PRIVATE);
apiKey = sharedPreferences.getString("apiKey", "User Tidak Ditemukan");
Log.d("getHeaders: ", apiKey);
// headers.put("Content-Type", "application/json; charset=utf-8");
// headers.put("Content-Type", "application/x-www-form-urlencoded");
headers.put("Authorization", apiKey);
return headers;
}
};
AppController.getInstance().addToRequestQueue(jsonObjRequest, tag_headers_req);
return addList;
}
Android Recycler View in tab layout
Your PagerAdapter class extends FragmentPagerAdapter. Then its constructor TAKES a FragmentPagerAdapter to initialize. So to initialize a FragmentPagerAdapter you need a FragmentPagerAdapter already?
I think that parameter is supposed to be a FragmentManager.
Cardview inside tab fragment
first Make Changes in your mainactivity .
here i added a navigation drawer and tablayout in mainactivity.
public class HomeActivity extends AppCompatActivity
implements NavigationView.OnNavigationItemSelectedListener {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_home);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(
this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
drawer.setDrawerListener(toggle);
toggle.syncState();
NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);
navigationView.setNavigationItemSelectedListener(this);
TabLayout tabLayout1 = (TabLayout) findViewById(R.id.tab_layout1);
tabLayout1.addTab(tabLayout1.newTab().setIcon(R.drawable.tab_ic_home));
tabLayout1.addTab(tabLayout1.newTab().setIcon(R.drawable.tab_ic_map));
tabLayout1.addTab(tabLayout1.newTab().setIcon(R.drawable.tab_ic_login));
tabLayout1.setTabGravity(TabLayout.GRAVITY_FILL);
final ViewPager viewPager1 = (ViewPager) findViewById(R.id.pager1);
final PagerAdapter1 adapter = new PagerAdapter1
(getSupportFragmentManager(), tabLayout1.getTabCount());
viewPager1.setAdapter(adapter);
viewPager1.addOnPageChangeListener(new TabLayout.TabLayoutOnPageChangeListener(tabLayout1));
tabLayout1.setOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
@Override
public void onTabSelected(TabLayout.Tab tab) {
viewPager1.setCurrentItem(tab.getPosition());
}
@Override
public void onTabUnselected(TabLayout.Tab tab) {
}
@Override
public void onTabReselected(TabLayout.Tab tab) {
}
});
}
@Override
public void onBackPressed() {
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
if (drawer.isDrawerOpen(GravityCompat.START)) {
drawer.closeDrawer(GravityCompat.START);
} else {
super.onBackPressed();
}
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.home, menu);
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_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
@SuppressWarnings("StatementWithEmptyBody")
@Override
public boolean onNavigationItemSelected(MenuItem item) {
FragmentManager fragmentManager = getSupportFragmentManager();
FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
// Handle navigation view item clicks here.
int id = item.getItemId();
RelativeLayout mainLayout=(RelativeLayout)findViewById(R.id.main_layout);
if (id == R.id.nav_project) {
ProjectFragment fragment = new ProjectFragment();
fragmentTransaction.replace(R.id.mainlayout, fragment);
fragmentTransaction.addToBackStack(null).commit();
}
}
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
drawer.closeDrawer(GravityCompat.START);
return true;
}
}
Then create a pager adapter.
here u can add fragments for your tabs..
i named it as PagerAdapter1.java.
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentStatePagerAdapter;
public class PagerAdapter1 extends FragmentStatePagerAdapter {
int mNumOfTabs;
public PagerAdapter1(FragmentManager fm, int NumOfTabs) {
super(fm);
this.mNumOfTabs = NumOfTabs;
}
@Override
public Fragment getItem(int position) {
switch (position) {
case 0:
HomeTabFragment1 tab1 = new HomeTabFragment1();
return tab1;
case 1:
HomeTabFragment2 tab2 = new HomeTabFragment2();
return tab2;
case 2:
HomeTabFragment3 tab3 = new HomeTabFragment3();
return tab3;
default:
return null;
}
}
@Override
public int getCount() {
return mNumOfTabs;
}
}
i just wanted a Recycler view in first tab. So i added code for recyclerview in HomeTabFragment1.java.
public class HomeTabFragment1 extends Fragment {
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View v=inflater.inflate(R.layout.home_tab_fragment_1, container, false);
RecyclerView rv = (RecyclerView)v.findViewById(R.id.home_recyclerview);
setupRecyclerView(rv);
return v;
I hope the rest you can do..
How to add recycler view or card view in fragments?
First Add support v7 library in your project then in xml file put this.
<android.support.v7.widget.RecyclerView
android:id="@+id/my_recycler_view"
android:layout_width="match_parent"
android:layout_height="match_parent">
</android.support.v7.widget.RecyclerView>
Then in your fragment put these lines.
scheduler_day_view_horizontal_recyclerview = (RecyclerView) v.findViewById(R.id.my_recycler_view);
layoutManager = new LinearLayoutManager(context, LinearLayoutManager.HORIZONTAL, false);
scheduler_day_view_horizontal_recyclerview.setLayoutManager(layoutManager);
scheduler_day_view_horizontal_recyclerview.setItemAnimator(new DefaultItemAnimator());
scheduler_day_view_horizontal_recyclerview.setHasFixedSize(true);
Then set adapter to the RecyclerView.
For more detail about cardview and Recycler view Please visit here
Related Topics
Date and Time Change Listener in Android
How to Get the Height and Width of the Android Navigation Bar Programmatically
Simple Parse JSON from Url on Android and Display in Listview
How to Achieve Ripple Animation Using Support Library
How to Hide Soft Keyboard When Activity Starts
How to Ignore Accent in SQLite Query (Android)
Broadcastreceiver Not Receiving Boot_Completed
Upload Large File in Android Without Outofmemory Error
Meaning of Top, Ascent, Baseline, Descent, Bottom, and Leading in Android's Fontmetrics
How to Get Camera Result as a Uri in Data Folder
How to Get the Touch Position in Android
Android Service Stops When App Is Closed
How to Implement Drawerarrowtoggle from Android Appcompat V7 21 Library
Android - How to Receive Broadcast Intents Action_Screen_On/Off
Remove Data from Notification Intent